在使用 vuex的时候出现 commit 未定义错误

出现的原因:

  • 书写错误
  • 当然,这个错误不是你单词书写错误
  • 只要的原因是因为你的这个 方法里面没有 commit 这个方法
  • 为什么没有?其实它是有的,只不过在 context 里面
  • 你可能是直接写 commit(xxx)了

错误展现过程:

首先我们先调用一下

<div><input type="button" @click="$store.dispatch('listMore')" value="加载更多"></div>
  • 为什么是 dispatch ,因为你不是用 commit 了吗?
  • 这个就是在 actions 里面调用 mutations 里面的方法的

然后就是代码:

actions = {
     login(context){
            commit("CHANGE_USERNAME")
        }
    }
};
  • 可以看到接受了一个参数,这个参数是它默认传的,你不能改变
  • commit 在 context 里面,但是你是直接写

正确调用的话可以这样来写

actions = {
     login(context){
            context.commit("CHANGE_USERNAME")
        }
    }
};

或者这样:

actions = {
     login({commit}){  //加 { }
            commit("CHANGE_USERNAME")
        }
    }
};
发布了74 篇原创文章 · 获赞 7 · 访问量 2201

猜你喜欢

转载自blog.csdn.net/qq_44163269/article/details/105268508