首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue生命周期和firebase:为什么我得到"TypeError:无法读取属性'url‘of null"?

Vue生命周期和firebase:为什么我得到"TypeError:无法读取属性'url‘of null"?
EN

Stack Overflow用户
提问于 2020-06-29 23:45:11
回答 1查看 78关注 0票数 0

我正在和一个问题作斗争。我在我的模板中获得了这个图像元素,如下所示:

代码语言:javascript
复制
<img :src="photo.url" :id="photo.filename" :alt="photo.title" v-if="photo.url" />

下面是我的data()函数:

代码语言:javascript
复制
data() {
    return {
      photo: null,
      // set variable during component creation to use when mounting
      anno: {}
    }

我有一个为img元素获取数据的方法,如下所示:

代码语言:javascript
复制
async mounted() {
    // get photo properties
    await this.getPhotoDoc()
    // initialize Annotorious and assign to 'anno' variable for use throughtout component
    this.anno = await new Annotorious({ image: this.photo.filename })

下面是我处理照片文档的方法:

代码语言:javascript
复制
    async getPhotoDoc() {
      try {
        const docRef = await photosCollection
          .doc(this.$route.params.id) // to be dynamic
          .get()
        if (docRef.exists) {
          // data() returns all data about the doc
          let photo = await docRef.data()
          this.photo = photo
        } else {
          console.log('no docs exist for this photo')
        }
      } catch (error) {
        console.log('Error getting document:', error)
      }
    }

我似乎无法在控制台中摆脱这个错误:

代码语言:javascript
复制
[Vue warn]: Error in render: "TypeError: Cannot read property 'url' of null"
found in
---> <PhotoDetail>
       <App> at src/App.vue
         <Root>

有谁发现了什么我可以调整的吗?

EN

回答 1

Stack Overflow用户

发布于 2020-06-30 00:42:09

因为照片是异步初始化的,所以在生命周期中有一个点,那就是photo是未定义的。对于这种情况,OP中的v-if不是一个足够的检查。将其更改为...

代码语言:javascript
复制
v-if="photo && photo.url"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62641810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档