vuex学习暂存

new_branch1
roger 2 years ago
parent 9287db0544
commit 58b5ae9e08
  1. 17
      20_脚手架/vue_code/src/components/Count.vue
  2. 29
      20_脚手架/vue_code/src/store/index.js

@ -1,6 +1,6 @@
<template> <template>
<div> <div>
<h1>当前求和为: {{sum}}</h1> <h1>当前求和为: {{$store.state.sum}}</h1>
<select v-model.number="n"> <select v-model.number="n">
<option value="1">1</option> <option value="1">1</option>
<option value="2">2</option> <option value="2">2</option>
@ -18,8 +18,7 @@ export default {
name: "Count", name: "Count",
data() { data() {
return { return {
n: 1, n: 1
sum: 0
} }
}, },
mounted() { mounted() {
@ -27,20 +26,16 @@ export default {
}, },
methods: { methods: {
add() { add() {
this.sum += this.n this.$store.commit('vuexAdd', this.n)
}, },
sub() { sub() {
this.sum -= this.n this.$store.commit('vuexSub', this.n)
}, },
addOdd() { addOdd() {
if (this.sum % 2) { this.$store.dispatch('vuexAddOdd', this.n)
this.sum += this.n
}
}, },
addWait() { addWait() {
setTimeout(()=>{ this.$store.dispatch('vuexAddWait', this.n)
this.sum += this.n
}, 500)
} }
} }

@ -7,12 +7,33 @@ import Vuex from 'vuex'
// 应用Vuex插件 // 应用Vuex插件
Vue.use(Vuex) Vue.use(Vuex)
// 准备actions-用于响应组件中的动作 // 准备actions-用于响应组件中的动作,业务逻辑需要写到actions中
const actions = {} const actions = {
vuexAddOdd(context, value) {
if (context.state.sum % 2) {
context.commit('vuexAdd', value)
}
},
vuexAddWait(context, value) {
setTimeout(() => {
context.commit('vuexAdd', value)
}, 1000
)
}
}
//准备mutations-用于操作数据 //准备mutations-用于操作数据
const mutations = {} const mutations = {
vuexAdd(state, value) {
state.sum += value
},
vuexSub(state, value) {
state.sum -= value
}
}
//准备state-用于存储数据 //准备state-用于存储数据
const state = {} const state = {
sum: 0
}
// 创建并导出store // 创建并导出store
export default new Vuex.Store({ export default new Vuex.Store({

Loading…
Cancel
Save