简体   繁体   中英

Vue lifecycle and firebase: Why do I get “TypeError: Cannot read property 'url' of null”?

I'm struggling with an issue. I got this image element in my template like so:

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

here's my data() function:

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

and I have a method that grabs data for the img element like so:

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

and here's my method for the photo doc:

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

I can't seem to get rid of this error in console:

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

any one spot anything I can tweak?

Since photo is initialized asynchronously, there's a point in the lifecycle when photo is undefined. The v-if in the OP is not an adequate check for this circumstance. Change it to...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM