mutations的类型常量
- 在使用mutations属性的过程中,在index.js文件中定义好mutations属性后,需要在组件中调用,使用this.$store.commit函数来调用,这种方法容易在调用mutations的函数时写错函数名
- 使用类型常量来进行mutations属性的调用。在store文件夹中新建js文件,名字叫做mutations-types,用来存放将要在mutations中定义的函数名
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
export const ADDCOUNT = 'addCount'
- 之后进入index.js文件,首先导入mutations-types.js文件,在mutations中定义函数。注意使用常量定义函数时需要使用该格式:[函数名] (参数){函数具体内容}
import {
INCREMENT,
DECREMENT,
ADDCOUNT
} from './mutations-types'
mutations: {
[INCREMENT](state) {
state.counter++;
},
[DECREMENT](state) {
state.counter--;
},
[ADDCOUNT](state, payload) {
state.counter += payload.count;
}
}
- 之后,在组件中引入该文件,使用commit函数进行调用
methods: {
add() {
this.$store.commit(INCREMENT);
},
sub() {
this.$store.commit(DECREMENT);
},
addCount(count) {
this.$store.commit({
type: ADDCOUNT,
count
});
}
}