无法在 docRef 函数中使用 this.$router.push(' ')

Unable to use this.$router.push(' ') inside docRef function

我正在尝试在我的 quasar 项目中使用 vue-router。 this.$router.push( ' ' ) 在页面上的任何地方都有效,但在此 docRef 块内除外。

我发现 this.$router.push 在同一组件中仍然有效。

这个路由器调用有效:

const userRef = this.$db.collection('users').doc(this.$fb.auth().currentUser.uid)
console.log('your id is' + this.$fb.auth().currentUser.uid)
userRef.set({
  accountUID: this.$fb.auth().currentUser.uid,
  accountChosen: true,
  accountType: 'user'
})
this.$router.push('../user/home')

这不起作用(在同一组件中):

  var docRef = this.$db.collection('users').doc(uid)
  docRef.get().then(function (doc) {
    data = doc.data().accountType
    if (data === 'user') {
      console.log('account is users')
      console.log(data)
      this.$router.push('./user/home')
    } else if (data === 'truck') {
      console.log('account is a truck')
      this.$router.push('./truck/home')
    } else {
      console.log('in else statement')
    }
  }).catch(function (error) {
    console.log(error)
  })

Chrome 控制台错误

TypeError: Cannot read property '$router' of undefined
        at eval (Check.vue?a4ce:44)

而不是:

docRef.get().then(function (doc) {

使用:

docRef.get().then((doc) => {

说明

箭头函数体块中的 this 指的是当前上下文,在您的例子中,是 Vue/component 实例。

但是当你使用 function 而不是箭头函数时,{} 块会创建一个新的上下文,改变 this 的语义,使其指向不同于this 在该函数之外。

换句话说,您的问题的发生是因为每个 function () {} 都有自己的上下文(它自己的 this),可以将其设置为其他内容。箭头函数 OTOH 继承声明它的上下文(this)。在这种情况下,由于您是在方法内部声明它,因此 this 是 Vue 实例。使用箭头函数保留它。使用 function() 并不能保证它(this 可以设置为其他内容,通常是这种情况)。

更多细节,我推荐MDN - Arrow Functions