无法从Vuejs方法和Firestore返回值 [英] Unable to return value from Vuejs method and firestore

查看:84
本文介绍了无法从Vuejs方法和Firestore返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从firestore OnSnapshot函数返回值,以便可以检索用户图像的url.我正在使用vuejs和firestore.而且我在vue的已创建属性中具有activeUserImg函数.

i want to return the value from the firestore OnSnapshot function so that i can retrieve the url of user image. I am using vuejs and firestore. And i have activeUserImg function in created property of vue.

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;

        }

每次显示时,返回的值都是未定义的.

and everytime it is the showing the value in return as undefined.

图片代码:

<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"/>


推荐答案

您可以将函数包装在

You can wrap the function in a promise and wait for when the result is available.

示例:

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);
            });
    });
}

然后,您可以通过以下方式访问值

Then, you can access the value by

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

const result = await activeUserImg()

console.log(result)

这篇关于无法从Vuejs方法和Firestore返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆