Eldair
Eldair

Reputation: 15

Vue component updated (rerendered) without reason

I have a component which is being updated (rerendered) without reason when parent's data item is changed even though it has nothing to do with component in question.

This is a simple reproduction https://codesandbox.io/s/gracious-cannon-s6jgp?file=/public/index.html if anyone can shed some light on this. (clicking button will fire update event in component)

If I remove element whose class is changed by vue (or remove dynamic class) it works as expected.

Upvotes: 0

Views: 1288

Answers (1)

gbalduzzi
gbalduzzi

Reputation: 10176

Because at each render you define new objects for the something property:

<hello-world :something="[{prop: 'vvv'},{prop: 'rrr'}]"></hello-world>
  • By clicking the button, you update the global data. The root element is rerendered.
  • During render, a new array with new objects is created as assigned at the something property in your component. While the objects created at each render are equal, they are different (i.e. they map to a different memory point)
  • Your component finds that the property something changes its reference, so it re-renders.

If you create an items property in your data and you pass that reference as the prop, the component is not re-rendered again:

main.js:

data: {
    active: false,
    items: [{ prop: "vvv" }, { prop: "rrr" }]
  },

index.html:

<hello-world :something="items"></hello-world>

Note that this behavior occurs because you are passing an array 8and it would be the same with an object. It would not happen with a constant variable of the primitive types (such as string, int, boolean, float), such as :something="'string'"

Upvotes: 1

Related Questions