0

I have the following data object in my Vue component:

 data() { return { items: {} } }, 

I make a check to see if it is empty and display a message:

 <tr v-if="items.data.length === 0"><p>There are currently no items.</p></tr> 

This code works, however I get the following error messages in the console:

Error in render: "TypeError: Cannot read property 'length' of undefined"

TypeError: Cannot read property 'length' of undefined

How can I check if an object is undefined? Sometimes the items object is filled with data and sometimes it isn't.

0

1 Answer 1

5

You need to ensure the data property is there first, and then check its length.

You can use the logical AND operator, which will return false if ‘items.data’ is coercible to false, so the second part, the ‘length’ check, won’t execute at all.

<tr v-if="items.data && items.data.length === 0"><p>There are currently no items.</p></tr> 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that fixed it, will mark this as the answer when I can.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.