1

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 ?

1
  • There's no difference if it's class instance or plain object for this case. You ask about a wrong thing. Please, provide stackoverflow.com/help/mcve if the problem persists Commented Sep 11, 2022 at 15:05

1 Answer 1

1

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
  }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.