javascript - 无法在 Vue js 变量中赋值
问题描述
当我分配从 firebase 集合中获得的值时,它给了我以下错误。
获取文档时出错:TypeError:无法在 eval 处设置未定义的属性“电子邮件”(Profile.vue?5a88:68)
下面是我的代码。
import firebase from 'firebase';
import fb from "@/firebase";
export default {
name: 'Upload',
data(){
return{
bio: '',
name: '',
email: '',
imageData: null,
picture: 'http://ssl.gstatic.com/accounts/ui/avatar_2x.png',
uploadValue: 0
}
},
created() {
this.setUsers();
},
methods:{
setUsers: () => {
var userRef = fb.collection("users").doc(firebase.auth().currentUser.uid);
userRef.get().then(doc => {
this.email = doc.data().email;
}).catch(function(error) {
console.log("Error getting document:", error);
});
},
}
}
为什么它给我这样的错误,我该如何解决?
解决方案
这将失去他在 firebase 回调函数中的作用域。
您必须将 this 对象分配给某个变量,然后您可以在 firebase 回调中使用它。
setUsers: () => {
const instance = this
var userRef = fb.collection("users").doc(firebase.auth().currentUser.uid);
userRef.get().then(doc => {
instance.email = doc.data().email;
}).catch(function(error) {
console.log("Error getting document:", error);
});
},