【问题标题】:Unable to assign value in Vue js Variable [duplicate]无法在Vue js变量中赋值[重复]
【发布时间】:2021-01-04 10:40:22
【问题描述】:

当我分配从 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);
      });
    },
 }
}

为什么会出现这种错误,我该如何解决?

【问题讨论】:

  • 问题似乎不是vue,而是js问题。检查这一行this.email = doc.data().email;。尝试控制台记录doc.data()doc.datadoc。我已经使用了一段时间的 firebase,但它与您尝试访问的密钥有关
  • setUsers: () => {} 应该是setUsers() {}(声明方法时不要使用箭头函数)

标签: javascript firebase vue.js vue-component


【解决方案1】:

这将失去他在 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);
  });
},

【讨论】:

  • 仍然报同样的错误。
  • 应该可以了。请发布您的错误
  • 获取文档时出错:TypeError:无法在 eval (Profile.vue?5a88:69) 处设置未定义的属性“电子邮件”
【解决方案2】:

您可以尝试控制台 instance.email 吗?

userRef.get().then(doc => {
console.log(instance.email)
})

它应该显示一个空字符串。如果它未定义,那么这就是错误的来源。

如果它不是未定义的,那么你应该检查doc.data().email是否存在。

【讨论】:

    猜你喜欢
    • 2020-08-28
    • 1970-01-01
    • 2017-07-05
    • 2017-07-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多