【问题标题】:Vuex: Cannot read property '$store' of undefined [duplicate]Vuex:无法读取未定义的属性“$store”[重复]
【发布时间】:2017-09-21 04:48:18
【问题描述】:

我已经在 vue.js 中建立了一个 store,并且可以访问组件计算部分的状态参数:

computed: {
    BASE_URL () {
    return this.$store.state.BASE_URL;  
  }

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

  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)
        });
    }  
 },

我在控制台收到此错误:

Uncaught (in promise) TypeError: Cannot read property '$store' of 未定义

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

这里有什么问题?我该如何解决?

【问题讨论】:

  • 你的应用注册vuex了吗? Vue.use(Vuex)
  • 是的,我做到了。正如我所说,vuex 可以在组件的computed 部分访问,但不能在方法的 promise 中访问。

标签: javascript vue.js vuex


【解决方案1】:

您使用的是 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)
        });
    }  

【讨论】:

  • 太棒了。这解决了这个问题。但是为什么我不能在 promise 中使用 vanilla JS?
  • 函数有自己的'this'实例,所以当你调用它时,你会得到你内部的函数实例,而不是vue实例。 vanilla javascript 中的典型解决方案是在函数外部创建一个临时变量,然后在函数内部使用它。例如 var self = this;注册:函数(){ self.$store.commit(); }
  • 仅供参考,箭头函数也是 "vanilla" JavaScript。
  • @Phil 感谢您提供的信息不知道我从中学到的教程是错误的。
猜你喜欢
  • 2018-04-21
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 2020-04-06
  • 1970-01-01
  • 2020-07-30
  • 2020-01-17
相关资源
最近更新 更多