1.State
//store.js
export default new Vuex.Store({
state: {
count: 0
},
})
//xxx.vue
import { mapState } from "vuex";
//映射到组件中的计算属性
computed: {
//映射到当前组件,可以直接使用
...mapState(["count"]),
},
2.Mutation
2.1Mutation触发方式
//store.js
//注:mutation中不能执行异步操作
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
add (state, step) {
state.count += step
}
},
})
//xxx.vue
methods: {
//-------触发Mutation的第一种方式,传参,2
addClick() {
this.$store.commit("add", 2);
},
//--------触发Mutation的第二种方式, 传参,3
...mapMutations(["add"]),
handle() {
this.add(3);
},
}
3.Action
3.1 action操作mutation(不带参数)
//store.js
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
add (state) {
state.count++
}
},
actions: {
// 必须通过context.commit() 触发mutation来修改state,actions不能直接修改state
addAsync (context) {
setTimeout(() => {
context.commit('add')
}, 1000)
}
}
})
<!-- xxx.vue -->
<!-- 异步操作 -->
<el-button type="primary" @click="btnHandle">1秒后+1</el-button>
methods: {
btnHandle() {
//dispatch用来触发action
this.$store.dispatch("addAsync");
},
},
3.2 携带参数
// store.js
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
add (state, step) {
state.count += step
}
},
actions: {
// 必须通过context.commit() 触发mutation来修改state,actions不能直接修改state
addAsync (context, step) {
setTimeout(() => {
context.commit('add', step)
}, 1000)
}
}
})
// xxx.vue
methods: {
btnHandle() {
//dispatch用来触发action
this.$store.dispatch("addAsync", 5);
// 触发action第二种方式
...mapActions(["addAsync"]),
},
},
4.Getters
// store.js
getters: {
showState (state) {
return '当前count值的2倍是:' + state.count * 2
}
},
// xxx.vue
computed: {
...mapGetters(["showState"]),
},