首页 > 解决方案 > Vue生命周期和firebase:为什么我会得到“TypeError:无法读取null的属性'url'”?

问题描述

我正在努力解决一个问题。我在我的模板中得到了这个图像元素,如下所示:

<img :src="photo.url" :id="photo.filename" :alt="photo.title" v-if="photo.url" />

这是我的data()功能:

data() {
    return {
      photo: null,
      // set variable during component creation to use when mounting
      anno: {}
    }

我有一个方法可以像这样抓取 img 元素的数据:

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

这是我的照片文档方法:

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

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

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

有人发现我可以调整的任何东西吗?

标签: javascriptgoogle-cloud-firestorevuejs2

解决方案


由于 photo 是异步初始化的,生命周期中有一个点 whenphoto是未定义的。OP 中的 v-if 不足以检查这种情况。将其更改为...

v-if="photo && photo.url"

推荐阅读