Vuex模块化 commit()时报错 unknown mutation type:xxx
写代码要细心,能开提示开提示,。。
·
废话不多说直接上问题:
我写了两个组件,准备练习Vuex的模块化
- 这是Count模块(计数作用)的js
increment方法触发后,由于逻辑十分简单我就直接给到了mutations
让他加
methods: {
increment() {
this.$store.commit("INCREMENT", this.n);
},
decrement() {
this.$store.commit("DECREMENT", this.n);
},
incrementOdd() {
this.$store.dispatch("incrementOdd", this.n);
},
incrementWait() {
this.$store.dispatch("incrementWait", this.n);
},
},
mutations: {
// 加
INCREMENT(state, value) {
state.sum += value;
},
// 减
DECREMENT(state, value) {
state.sum -= value;
}
},
state: {
sum: 0,
bigSum: 0,
},
- 这是Person模块(添加人员作用)的js
add方法触发后将信息封装成对象直接给到mutations,然后一个unshift新增即可
methods: {
add() {
const personObj = { id: nanoid(), name: this.name };
console.log(this.$store);
this.$store.commit("ADD_PERSON", personObj);
this.name = "";
},
},
mutations: {
ADD_PERSON(state, personObj) {
state.personList.unshift(personObj);
},
},
然后这是storejs
import Vue from 'vue'
// 引用vuex
import Vuex from 'vuex';
// 使用vuex
Vue.use(Vuex)
import CountOptions from './count';
import PersonOptions from './person';
// 创建并暴露store
export default new Vuex.Store({
modules:{
countAbout:CountOptions,
personAbout:PersonOptions,
}
})
就这样,run起来后,
触发increment(数字+) ==> 成功
触发add(加一个人) ==> unknown mutation type:ADD_PERSON
于是我把$store捞出来,找到_mutations
发现我的添加人员的add指向的的mutation 外面包了一层,
完事我将这一层加上去,成功实现,
然后我将Count的加上countAbout反而报错
那么问题来了,为啥我两个模块的写法是一样,然后调用的模块的情况也是一样的(count.vue==>count模块,person.vue==>person模块),
一个包了一个没包,
于是我怀疑是引入顺序的问题,觉得第一个引入的模块不包,
于是我将模块的引入,声明甚至组件的顺序都调换了顺序,,
然而并没有什么软用。。。
于是我写了一个临时的test模块。分别copy Count,Person模块的js,
然后我以为是命名的问题,因为我的两个模块的命名一个有下划线,一个没有下划线,于是:
发现并不是
于是我有写了两个测试模块 test demo
发现除了count,其他都包了
最后发现是我的count的开启命名空间namespaced的d忘了写,,,,
对不起,我是憨憨
更多推荐
已为社区贡献1条内容
所有评论(0)