为什么我不能在 firebase 'then' 回调中访问 vuejs 'this '?

Why can't I access vuejs 'this ' within firebase 'then' callbacks?

我正在尝试使用 firebase 向我的 vuejs 应用程序添加身份验证。 注销用户后,应将用户送回登录页面。我在 HelloWorld.vue 文件的脚本中实现了以下代码:

import firebase from 'firebase'

  export default {
    name: 'HelloWorld',
    data () {
      return {
        msg: 'Welcome to Your Vue.js App'
      }
    },
    methods: {
      logout () {
        firebase.auth().signOut().then(function () {
          this.$router.push('login')
        })
      }
    }
  }

但是我从我的 vuejs 开发工具中得到以下错误:

TypeError: this is undefined
[Learn More]
app.js%20line%201954%20%3E%20eval:40:9
logout/<
HelloWorld.vue:37
Pb/e.a</e.g<
auth.js:23
Yb
auth.js:26
Ub
auth.js:26
h.Qb
auth.js:25
Cb
auth.js:19

在 firebase 回调中引用 this 对象

这个.$router.push('login')

我需要帮助来弄清楚为什么我不能在回调中访问它,以及我该如何解决这个问题。提前致谢。

在函数中,'this' 绑定到函数本身而不是 vue 实例。解决方法:

methods: {
  logout () {
    const that = this      \ the ES5 var is also possible
    firebase.auth().signOut().then(function () {
      that.$router.push('login')
    })
  }
}

您可以使用 arrow function 来解决这个问题,因为 this 在另一个函数中时没有作用于 vue 实例。

methods: {
  logout () {
    firebase.auth().signOut().then(() => { // arrow syntax
      this.$router.push('login')
    })
  }
}

我个人更喜欢这个,因为它节省了另一个变量声明。

另一种方法是使用 bind(this):

methods: {
  logout () {
    firebase.auth().signOut().then(function () { 
      this.$router.push('login')
    }.bind(this)) // bind added.
  }
}