【问题标题】:How can I set the variable with firebase information如何使用 Firebase 信息设置变量
【发布时间】:2020-01-31 23:17:57
【问题描述】:

我正在尝试使用从 firebase 上的 get() 函数获得的信息设置一个变量,但我做不到。

 export default {
    name: "customer-navigation",
mixins: [navigationMixin],
components:{AppSnackBar, authModule,AuthForm},

data () {
      return {
    drawer: false,

    items: [
      { title: this.$t('navigation.home'), icon: 'home', to: '/' },
      { title: this.$t('navigation.shop'), icon: 'shopping_basket', to: 
 '/shop' },
      { title: this.$t('navigation.cart'), icon: 'shopping_cart', to: 
 '/cart' },
      { title: this.$t('navigation.orders'), icon: 'view_headline', to: 
 '/orders' },
    ],
    img_url: "" ,
    nombreFire: "",
  }
},
methods: {
  getInfo(){      

 db.collection('users').doc(authModule.state.user.uid).get().then(function(doc) {        
      this.img_url = doc.data().img_url
    })     




  }
}


}

Uncaught (in promise) TypeError: Cannot set property 'img_url' of undefined 在评估时,这是我得到的错误

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore vuex


    【解决方案1】:

    您的错误表明它无法设置undefined 的属性img_url。查看您的代码,您正在为对象this 设置属性img_url

    this 未定义,因为您处于回调函数中。你可以做的是修改你的getInfo方法如下:

    
    getInfo() {
      const vm = this; //this is the vue module.
      db.collection('users').doc(authModule.state.user.uid).get().then(doc => {
      vm.img_url = doc.data().img_url; //set the passed-in 'this'
    });
    

    This question can provide more insight on scoping 'this' in callbacks

    【讨论】:

    • 请注意,如果您使用箭头函数,则不需要使用const vm = this;,您可以使用this,因为在箭头函数中,this 不指代函数的所有者。实际上,您链接到的 SO 答案也提到了这一点。
    猜你喜欢
    • 2015-09-18
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    相关资源
    最近更新 更多