作者:手机用户2502939381 | 来源:互联网 | 2023-02-10 08:10
我需要更新Firebase回调中的Vue属性,如下所示,但它无法正常工作.这段代码
methods: {
sign_out : function(e) {
this.item_count = 0
}
}
工作,但在承诺回调中设置属性时:
methods: {
sign_out : function(e) {
firebase.auth().signOut().then(function() {
this.item_count = 0
})
},
在这种情况下如何设置属性的值?
1> Bert..:
您this
的回调中指向错误的对象.有几种方法可以解决这个问题.
this
在封闭中捕获.
methods: {
sign_out : function(e) {
var self = this;
self.item_count = 0
firebase.auth().signOut().then(function() {
self.item_count = 0
})
}
使用胖箭头.
methods: {
sign_out : function(e) {
this.item_count = 0
firebase.auth().signOut().then(() => this.item_count = 0)
}
}
使用bind().
methods: {
sign_out : function(e) {
this.item_count = 0
firebase.auth().signOut().then(function() {
this.item_count = 0
}.bind(this))
}
胖箭头在所有现代浏览器中都不起作用,因此只有在编译为es5时才使用它们.