Ram*_*ngh 4 firebase firebase-authentication vue-router vuejs2
我正在尝试使用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')
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是我从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
Run Code Online (Sandbox Code Playgroud)
在Firebase回调中引用this对象
这个。$ router.push('login')
我需要帮助以弄清楚为什么我不能在回调中访问它以及如何解决该问题。提前致谢。
您可以使用arrow函数来解决此问题,因为this在另一个函数中,该问题不限于vue实例。
methods: {
logout () {
firebase.auth().signOut().then(() => { // arrow syntax
this.$router.push('login')
})
}
}
Run Code Online (Sandbox Code Playgroud)
我个人比较喜欢这样做,因为它可以保存另一个变量声明。
另一种方法是使用bind(this):
methods: {
logout () {
firebase.auth().signOut().then(function () {
this.$router.push('login')
}.bind(this)) // bind added.
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
828 次 |
| 最近记录: |