[英]Vue.js - Can't access computed properties from methods
我在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
})
// ...
}
這是計算的道具的樣子:
message: {
get () {
return this.auth.message // mapState(['auth'])
},
set (value) {
this.$store.commit('authMessage', value)
}
}
我很確定這個問題與它在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
})
或者,如果您使用的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
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.