0

Is it known that if you display an Object's property in a Vue.js template, and the object is undefined - that will crash the component. Regular variables are no problem if they're undefined.

This behavior is a killjoy. In my situation, which seems pretty generic, what is the best way to avoid this problem?

So I store data in a NoSQL database i.e. Mongo, and have a Vue.js component to view and modify the documents in the collection. Which works well.

But if I add an Object with properties to my schema (for example address with zip, state...), and update the component to display them, now all the components in my webapp will crash that display these documents because the object isn't in the data. Only new documents (with the new object) will show correctly, unless I go thru the database and add this "address" object to every existing document.

It would be great if the template could give the user an opportunity to view blank or add data that isn't already in the database.

What is a best practice in such a situation?

Should objects simply be avoided here?

1
  • Give properties default/blank values, or use conditional rendering. Commented Oct 3, 2017 at 1:23

1 Answer 1

4

This doesn't really have anything to do with Vue. You're dealing with a javascript error here. You can't reference a property of a null/undefined variable. The easy way around this is to use the && operator to check for the object.

someObj && someObj.property

If someObj is falsy, the right side is never evaluated. Note that when the left side is truthy, && returns the right side. Details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

If you want a specific blank value, you can do this

someObj ? someObj.property : "Default value"
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.