带有:src的VUE图像在第一次渲染时不显示

时间:2019-06-10 13:03:52

标签: javascript firebase vue.js firebase-storage

您好,我的头像组件遇到问题,我从vuex存储中存储的url加载的图像仅在第二个渲染中不会显示在第一个渲染中。

这是我的头像组件

<template>
   <img :src="getAvatarUrl()"/>
</template>

<script>
export default {
 methods: {
   getAvatarUrl() {
     return this.$store.state.user.userAvatarUrl
   }
 }
}
</script>

这是我通过App.vue在商店中提交图像URL的方式:

  created() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        let avatarRef = firebase.storage().ref().child(`avatars/${this.$store.state.user.displayName}`)
        avatarRef.getDownloadURL().then(url => {
          this.$store.commit('userAvatarUrl', url)
        })
      }
   })
}

该头像组件中的这张图片不会第一次呈现, 我必须在另一条路线上导航,然后再回来查看。 我试图用:key强制在所有生命周期钩子上重新渲染,并使用this。$ nexttick,但这也不起作用。 感谢您的帮助

1 个答案:

答案 0 :(得分:3)

这是因为在请求完成之前存储区不包含映像路径,并且在DOM和组件已呈现后 ,请求可能会完成。

您只需要使用computed property即可:

<template>
   <img :src="avatarUrl"/>
</template>

<script>
export default {
 computed: {
   avatarUrl() {
     return this.$store.state.user.userAvatarUrl
   }
 }
}
</script>