Home > Mobile >  Rendering properties of class objects in VueJS
Rendering properties of class objects in VueJS

Time:09-12

today I came across a problem. I have element in template which is set up like this:

<div v-if="object">{{ object.property }}</div>

It was constantly throwing an error which said cannot read properties of undefined reading 'property' I was so confused why there is an error like this when there is the v-if and in console it read properly. After that I realised that the object is an instance of class I've defined, it's not a normal js object. Can someone explain why Vue can't read properties of a class instance ?

CodePudding user response:

Most data properties in Vue have a value that will loosely equate to true unless it is a primitive value such as a number or a Boolean.

In your case what I resort to using is v-if="'property' in object", this works as long as the value of object never starts as or becomes null, An initial value of an empty object is required.

export default {

  data: () => ({
    object: {}
  }),

  beforeMount () {
    console.log('property' in this.object) // Logs false
  },

  mounted () {
    this.object = {
      property: 'some value'
    }
    console.log('property' in this.object) // Logs true
  }

}
  • Related