Firebase 无法在docRef函数内使用此。$router.push(';';)功能
我试图在我的quasar项目中使用vue路由器Firebase 无法在docRef函数内使用此。$router.push(';';)功能,firebase,vue.js,quasar-framework,quasar,Firebase,Vue.js,Quasar Framework,Quasar,我试图在我的quasar项目中使用vue路由器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
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')
这不起作用(在同一组件中):
Chrome控制台错误
TypeError: Cannot read property '$router' of undefined
at eval (Check.vue?a4ce:44)
而不是:
docRef.get().then(function (doc) {
使用:
解释
箭头函数体块中的此
表示当前上下文,在您的示例中,指的是Vue/组件实例
但是当您使用函数
而不是箭头函数时,{}
块会创建一个新的上下文,更改this
的语义,使其指向该函数之外的this
换句话说,问题的出现是因为每个函数(){}
都有自己的上下文(它自己的this
),可以设置为其他内容。箭头函数OTOH继承声明它的上下文(this)。在本例中,由于您是在方法中声明它,因此this
就是Vue实例。使用箭头函数可以保留它。使用函数()
关于更多细节,我推荐
docRef.get().then(function (doc) {
docRef.get().then((doc) => {