好吧,我明白了。感謝@Daniel D提供的關於綁定爲數組或對象的技巧。因此,事實證明,我不必在firebase引用掛鉤中執行此操作,例如,我只需將其綁定爲mounted()
鉤子中的數組即可。我只是在數據申報空cart: []
,然後填充它,像這樣:
<script>
import changeColorMixin from '../mixins/changeColorMixin'
import animateFunction from '../mixins/animationMixin'
import Firebase from 'firebase'
import app from '../firebaseApp'
export default {
data(){
return{
isLoggedIn: '',
cart: []
}
},
methods:{
changeColor: changeColorMixin,
animateEntrance: animateFunction,
promptLogin: function(){
console.log('you need to login!');
},
chooseSize: function($event){
$($event.target).parents().eq(2).addClass('chosen');
},
closeOrder: function($event) {
$($event.target).parents().eq(2).removeClass('chosen');
},
makeOrder: function($event){
var $this = this;
Firebase.auth().onAuthStateChanged(function(user){
if(user){
var cartRef = app.database().ref('users/' + user.uid + '/cart');
var currentCart;
cartRef.once('value', function(result) {
currentCart = result.val();
var size = $($event.target).html();
var name = $($event.target).parents().eq(2).attr('id');
app.database().ref('users/' + user.uid + '/cart/' + name + '/count').once('value', function(snap){
var count = snap.val();
if(count > 0){
count = count + 1;
}else{
count = 1;
}
cartRef.child(name).set({
size: size,
count: count,
name: name
});
});
});
}else{
console.log('gotta login mate');
}
});
}
},
mounted(){
Firebase.auth().onAuthStateChanged(user => {
if(user){
this.isLoggedIn = true;
var cartRef = app.database().ref('users/' + user.uid + '/cart');
this.$bindAsArray('cart', cartRef);
}else{
this.isLoggedIn = false;
}
});
this.animateEntrance();
this.changeColor();
}
}
</script>
正如我所說的大感謝@Daniel d
你需要這樣您異步綁定參考,*後接線起來*'onAuthStateChanged'激發。你必須等待它才能準確地知道用戶ID和用戶是否登錄。 –
我有類似的問題,我正在用'firebase.auth()。currentUser'這樣做:我嘗試在'created()'上檢查'uid',並設置它,然後設置它。然後,使用'this.uid'而不是'firebase.auth()。currentUser.uid',但沒有奏效。如果有的話,我也在尋找更好的解決方案。 –