TypeError: Cannot read property '$store' of undefined Vue中·无法使用this.$store访问Vuex的全局数据

------------恢复内容开始------------

methods: {
    login() {
      console.log(this.email,this.password)
      let result = toLogin(this.email,this.password)
      result.then(function(value){
        console.log(value)
        this.$store.commit('upStatus',value.status,value.message,!this.$store.flag)      //无法使用this.$store
      })
      
      // console.log(getPostById('5eb82f6f720a63305c760a3d'))
    }
  },

这是因为此时的this是:undefined!在result.then这个方法改变了this的指向
解决方案:

result.then((value) => {
      console.log(value)
      this.$store.commit('upStatus',value.status,value.message,!this.$store.flag)
   })

使用箭头函数,
------------恢复内容结束------------

posted @ 2020-05-12 00:47  一只小鲸鱼  阅读(13503)  评论(0)    收藏  举报