导出默认的新Vuex.Store和Mutations

时间:2018-09-22 19:24:02

标签: javascript vue.js vuex

我在使用commit时遇到问题,如here所述。可能的问题是我使用export default new Vuex.Store而不是export const store = new Vuex.Store。但是当我更改此设置时,我在this topic中遇到了问题。

Here是我的JS文件,在这里我使用Vuex,并且我想调用commit

actions: {
  signUserIn(payload) {
    payload.password;
    var params = new URLSearchParams();
    params.append("grant_type", "password");
    params.append("username", "admin");
    params.append("password", "adminPassword");
    axios({
      method: "post",
      url: "http://localhost:8090/oauth/token",
      auth: { username: "my-trusted-client", password: "secret" },
      headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
      },
      data: params
    }).then(function(response) {
      const user = {
        login: payload.username
      };
      localStorage.setItem("access_token", response.data.access_token);
      this.commit("setUser", user);
    });
  }
},

当我运行此程序并尝试调用signUserIn时,控制台中出现此错误:TypeError: Cannot read property 'commmit' of undefined

我不知道在这种情况下我可以在Google中键入什么。

2 个答案:

答案 0 :(得分:0)

我相信您输入了错误的内容。它应该是commit,而不是commmit

编辑:看到文件,请尝试改用箭头功能。

axios({
    method: "post",
    url: "http://localhost:8090/oauth/token",
    auth: { username: "my-trusted-client", password: "secret" },
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
    },
    data: params
  }).then(response => {
    const user = {
      login: payload.username
    };
    localStorage.setItem("access_token", response.data.access_token);
    this.commit("setUser", user);
  });

这是因为没有它,您将失去this的上下文。使用箭头功能,this仍然是外部上下文中的this。另外,不确定在这种情况下是否需要this,但可以尝试使用或不使用它。 (我说了太多遍了)

答案 1 :(得分:0)

请注意,您的操作方法的签名不正确。 Vuex docs表明action方法将Vuex上下文(包含commit方法)作为第一个参数,将有效载荷作为第二个参数:

// signUserIn(payload) { // DON'T DO THIS
signUserIn(context, payload) {

使用当前代码,您会注意到payload.usernamepayload.password未定义。

demo of your action with the bug

您的操作方法应如下所示:

actions: {
  signUserIn(context, payload) {
    axios.post().then(response => {
      context.commit('foo', foo);
    });
  }
}

demo of fix