【问题标题】:Unable to assign to data var in VueJS after Firestore storageFirestore 存储后无法分配给 VueJS 中的数据变量
【发布时间】:2021-07-04 00:03:33
【问题描述】:

大家好,我遇到了一个问题,我的数据被改回原来的分配。例如,我有以下数据:

 data() {
    return {
        uid: "",
        pic: "hello",
    }
},

使用下面的函数,警报返回“hello”

created() {
    this.uid = fb.auth().currentUser.uid;
    this.getprofilepic();
},

** getprofilepic 函数

getprofilepic() {
    fb.storage().ref('users/' + this.uid + '/profile.jpg').getDownloadURL().then(imgurl => {
        this.pic = imgurl;
    })
    alert(this.pic);           // returns "hello"
},

如果我将警报放入 fb.storage...,它会返回正确的路径,如下所示:

getprofilepic() {
    alert("getting profile pic")
    fb.storage().ref('users/' + this.uid + '/profile.jpg').getDownloadURL().then(imgurl => {
        this.pic = imgurl;
        alert(this.pic);     // returns correct path;
    })
    
},

是否有理由再次覆盖数据?预先感谢您的任何帮助! :) 我想 v-bind:src 从 firebase 存储中获取照片的路径,但“pic”返回“hello”。您可以在下面找到我的 html 代码:

<b-avatar :src = "pic" id = "profilepic" class="mr-5" size="8em"></b-avatar>

【问题讨论】:

  • 每次特定页面再次呈现时,数据属性中的所有分配都会设置为其初始分配。
  • 嗨@YashMaheshwari,感谢您的评论。你的意思是调用 fb.storage().ref.... 会刷新页面,还有没有办法解决这个问题?谢谢

标签: javascript firebase vue.js firebase-storage


【解决方案1】:

如果我正确理解您的问题,原因是 getDownloadURL() 方法是异步的。仅当方法返回的Promise 将被满足时,调用此函数的结果才可用。这就是我们使用then() 方法的原因:传递给then() 的处理函数将返回URL 的值。

上一段中重要的是 will 的使用:该方法是异步,因此不会立即返回结果。但是,JavaScript 代码继续执行:这就是为什么行 alert(this.pic); 会使用初始 hello 值执行。

试试下面的代码:

getprofilepic() {
    fb.storage().ref('users/' + this.uid + '/profile.jpg').getDownloadURL().then(imgurl => {
        alert(imgurl);   // <----- See the change here
        this.pic = imgurl;
    })
    alert(this.pic);           // returns "hello"
},

在控制台中,您应该首先看到hello,然后是 URL 值。

结论:只能在then()块中获取getDownloadURL()方法的调用结果。


您会在 Internet 和 SO 上找到很多关于如何从异步调用返回响应的文献。一个很好且完整的例子:How do I return the response from an asynchronous call?。 (实际上,我本可以将您的问题标记为该问题的重复。)

【讨论】:

  • 嗨@RenaudTarnec,感谢您的详细解释。我了解它现在是如何工作的,但是很好,我的实际问题是我想 v-bind:src = "profilepic" 并且数据 profilepic 显示“hello”而不是实际路径。有没有办法解决这个问题?
  • 要么以空值开始,要么以“Loading...”值开始Vue.js lifecycle hook之一中执行此调用,例如created之一, i 这样,只有在返回正确的值时才会显示组件。
  • 我确实在 created() 中绑定了 getprofilepic() 函数,并使用 v-bind:src = "pic" 调用了 var pic,如上所示(已编辑)。变量 pic 仍然显示错误的数据:改为显示“hello”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-13
  • 2021-07-01
  • 1970-01-01
  • 2018-08-10
  • 2021-11-04
  • 1970-01-01
  • 2013-04-22
相关资源
最近更新 更多