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

标签 javascript vue.js vuex

<分区>

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

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 undefined

我也尝试过不使用 this$store 但得到同样的错误。

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

最佳答案

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

关于javascript - Vuex:无法读取未定义的属性 '$store',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46335667/

相关文章:

javascript - 防止在 TinyMCE 中输入默认键盘事件

javascript - 如何根据Javascript中的多个键对对象数组进行分组?

vue.js - vue-router:使用命名 View 时将 Prop 传递到组件中

javascript - 如何在 VueJS 中使类的 "virtual"getter 响应式

javascript - Vue.js - 我该如何解决 [Vue 警告] : Error in render: "TypeError: Cannot read property ' port' of undefined"?

javascript - react : Accessing a target element as 'this'

javascript - 如何使用一个 jquery 在同一页面中制作多个阅读更多按钮?

javascript - 在 VueJS 中用相同的组件包装三个特定的路由

javascript - vue momentjs 从时间戳实时更新相对时间

javascript - 在 vuex 状态下包含 html 标签