Vuex:无法读取未定义的属性'$ store'

Kar*_*lom 4 javascript vue.js vuex

我在vue.js中建立了一个商店,可以访问compoenent的计算部分中的状态参数:

computed: {
    BASE_URL () {
    return this.$store.state.BASE_URL;  
  }
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试在同一组件的方法中访问商店时:

  methods: {

    register: function () {
          axios.post( this.BASE_URL + "/web/register", {
          username: this.username,
          password: this.password,
          email: this.email
        }).then(function(data){
          this.$store.commit('saveToken', data.token);
          console.log('token is set to:',  this.$store.state.token)
        });
    }  
 },
Run Code Online (Sandbox Code Playgroud)

我在控制台上收到此错误:

未捕获(承诺)TypeError:无法读取未定义的属性'$ store'

我也试过但$store没有this得到同样的错误.

这有什么不对?我该如何解决?

Jer*_*era 16

您使用的是javascript函数而不是箭头函数.试试这个它应该工作.

 methods: {
    register () {
          axios.post( this.BASE_URL + "/web/register", {
          username: this.username,
          password: this.password,
          email: this.email
        }).then( (data) => {
          this.$store.commit('saveToken', data.token);
          console.log('token is set to:',  this.$store.state.token)
        });
    }  
Run Code Online (Sandbox Code Playgroud)

  • 函数有自己的'this'实例,所以当你调用它时,你得到你内部函数的实例,而不是vue实例.在vanilla javascript中的典型解决方案是在函数外部创建一个临时变量,然后在函数内部使用它.例如var self = this; register:function(){self.$ store.commit(); } (7认同)
  • 仅供参考,箭头函数也是*“ vanilla” * JavaScript。 (2认同)