Shaun
Shaun

Reputation: 1601

Stop null warnings for properties during render

I have a component that renders it's template with for example a span that looks like:

<span>{{item.name}}</span>

the item is passed in as a property:

props: {
        item: null
    },

when the component is first mounted item is null, so when the render happens I get this in the logs:

[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of null"

If I create a computed property like this:

computed: {
        name() {
            if (this.item != null) {
                return this.item.name
            }
        }
    },

And then put name instead of item.name in the render it works fine, but is there a way to tell Vue to stop complaining about subproperties being null since it doesn't seem to care about root properties being null?

Maybe @LinusBorg knows?

Upvotes: 2

Views: 3990

Answers (1)

thanksd
thanksd

Reputation: 55644

That's not Vue-specific. Vue is simply warning you that you have a javascript TypeError. The error is being caused because you can't access a property of a null value in javascript.

I would just set the default value of your item prop to an empty object instead of null:

props: {
  item: { type: Object, default: () => ({}) }
}

Upvotes: 6

Related Questions