【问题标题】:Unable to return value from Vuejs method and firestore无法从 Vuejs 方法和 firestore 返回值
【发布时间】:2020-01-10 08:26:32
【问题描述】:

我想从 Firestore OnSnapshot 函数返回值,以便我可以检索用户图像的 url。我正在使用 vuejs 和 firestore。我在 vue 的 created 属性中有 activeUserImg 函数。

activeUserImg: function () {
           const u = firebase.auth().currentUser;
firebase.firestore().collection('Colleges').doc(u.uid).onSnapshot(function(doc) {

         var img_arr=[];
        this.img_arr.push(doc.data())
        this.img= doc.data().logo
    });
      return this.img || this.$store.state.AppActiveUser.img;

        }

并且每次都将返回的值显示为未定义。

图片代码:

<img
v-if="activeUserImg.startsWith('http')"
key="onlineImg"
:src="activeUserImg"
alt="user-img"
width="40" height="40"/>
<img
v-else
key="localImg"
:src="require(`@/assets/images/portrait/small/${activeUserImg}`)"
alt="user-img"
width="40" height="40"/>


【问题讨论】:

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


【解决方案1】:

return 语句应该在 firestore 回调中,如下所示

activeUserImg: function () {
           const u = firebase.auth().currentUser;
firebase.firestore().collection('Colleges').doc(u.uid).onSnapshot(function(doc) {

     var img_arr=[];
    this.img_arr.push(doc.data())
    this.img= doc.data().logo
    return this.img || this.$store.state.AppActiveUser.img;
});


    }

【讨论】:

  • 我试过这个。它不起作用。它仍然没有返回存储在 firestore 文档字段中的 url 地址
【解决方案2】:

您可以将函数包装在 promise 中,然后等待结果可用。

例子:

activeUserImg: () => {
    return new Promise(function(resolve, reject) {
          const u = firebase.auth().currentUser;

          firebase
            .firestore()
            .collection('Colleges')
            .doc(u.uid)
            .onSnapshot(function(doc) {
                var img_arr=[];
                this.img_arr.push(doc.data())
                this.img= doc.data().logo

                // return the result
                resolve(this.img || this.$store.state.AppActiveUser.img);
            });
    });
}

然后,您可以通过

activeUserImg.then(result => {
   console.log(result);
})

或者

const result = await activeUserImg()

console.log(result)

【讨论】:

  • 我使用了相同的功能,但仍然没有显示图像。我已经在主代码中添加了图像代码
  • 您是否从 firebase 获取图像结果?您是否对从 firebase 获得的 doc 数据进行了控制台,并且它在那里?你想复制到别人可以看的地方吗?
  • console.log(result) 在控制台中显示 url 但在 标签中调用的函数不显示图像
  • 好的。现在这是一个与问题完全不同的问题。如果您确定图片在资产文件夹中可用,请尝试使用: :src="/assets/images/portrait/small/${activeUserImg()}" 作为“v-else”
  • 实际上我正在尝试从以 url 形式存储的 firebase firestore 中检索图像(存储在 logo 中)。我的代码采用函数activeUserImg()返回firebase图像url(在v-if的if部分)或本地图像(在v-else)部分的格式。目前 activeuseUserImg 无法从我的数据库中返回字段“logo”的值
猜你喜欢
  • 2018-10-15
  • 1970-01-01
  • 2021-01-13
  • 2018-03-19
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 2018-12-13
相关资源
最近更新 更多