【问题标题】:Vue.js - Can't access computed properties from methodsVue.js - 无法从方法访问计算属性
【发布时间】:2018-03-02 18:17:06
【问题描述】:

我在 Vue 组件中有一个登录方法,它使用 firebase 来登录用户。我正在使用计算属性 usermessagehasErrors。当这个方法运行时,它进入catch函数,但是出现了这个错误: Uncaught TypeError: Cannot set property 'message' of undefined。我尝试直接更改 vuex 状态(因为这是计算道具所做的),但这会产生相同的错误。这是我正在使用的方法:

login: function (event) {
  // ... more stuff
  // Sign-in the user with the email and password
  firebase.auth().signInWithEmailAndPassword(this.email, this.password)
    .then(function (data) {
      this.user = firebase.auth().currentUser
    }).catch(function (error) {
      this.message = error.message
      this.hasErrors = true
    })
  // ...
}

这是计算出来的 prop 的样子:

message: {
  get () {
    return this.auth.message // mapState(['auth'])
  },
  set (value) {
    this.$store.commit('authMessage', value)
  }
}

我很确定问题与它位于Promise 中有关。 那么如何访问 firebase Promise 中的计算属性呢?

【问题讨论】:

  • this 不是您认为的回调内部的内容 - 可能想了解this 的工作原理以及如何解决它。

标签: javascript vue.js


【解决方案1】:

回调中的this 指的是回调本身(或者更确切地说,正如所指出的,回调的执行上下文),而不是 Vue 实例。如果你想访问this,你要么需要将它分配给回调之外的东西:

  // Assign this to self
  var self = this;

  firebase.auth().signInWithEmailAndPassword(this.email, this.password)
    .then(function (data) {
      self.user = firebase.auth().currentUser
    }).catch(function (error) {
      self.message = error.message
      self.hasErrors = true
    })

或者,如果您使用的是 ES2015,请使用 arrow function,它没有定义自己的 this 上下文:

  firebase.auth().signInWithEmailAndPassword(this.email, this.password)
    .then(data => {
      this.user = firebase.auth().currentUser
    }).catch(error => {
      this.message = error.message
      this.hasErrors = true
    })

【讨论】:

  • 它不是指回调,它指的是回调的执行上下文,不管它是什么。
  • 是的,我知道我一输入就会得到某人的回复。 ;)
猜你喜欢
  • 2021-11-07
  • 2021-03-13
  • 2017-08-09
  • 2019-02-23
  • 2019-08-04
  • 2019-01-21
  • 2023-03-19
  • 2019-05-07
  • 1970-01-01
相关资源
最近更新 更多