我在Vue组件中有一个使用firebase登录用户的登录方法.我使用的计算性能user,message以及hasErrors.当这个方法运行时,它进入catch函数,但是这个错误出现了:
Uncaught TypeError: Cannot set property 'message' of undefined.我已经尝试直接更改vuex状态(因为这是计算的prop所做的),但这会产生相同的错误.这是我正在使用的方法:
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
})
// ...
}
Run Code Online (Sandbox Code Playgroud)
这是计算的道具的样子:
message: {
get () {
return this.auth.message // mapState(['auth'])
},
set (value) {
this.$store.commit('authMessage', value)
}
}
Run Code Online (Sandbox Code Playgroud)
我很确定这个问题与它内部的问题有关Promise.那么如何在firebase中访问计算属性Promise呢?
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
})
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用的是ES2015,请使用箭头功能,该功能不会定义自己的this上下文:
firebase.auth().signInWithEmailAndPassword(this.email, this.password)
.then(data => {
this.user = firebase.auth().currentUser
}).catch(error => {
this.message = error.message
this.hasErrors = true
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2751 次 |
| 最近记录: |