Giorgi
Giorgi

Reputation: 383

Vue component not updating after parent state change

I have Vue component which receives json data from props, after this render child components using v-for and pass this data as prop. Everything works fine until i try to remove one item from this list, when i remove it, it removes element incorrectly. In vue devtools i see that parent receives data correctly but not renders it properly. can anyone help me? here is my code: https://gist.github.com/giokaxo/3d291b9b7b8ef97f81dc83799c430302

Upvotes: 0

Views: 1362

Answers (2)

Roy J
Roy J

Reputation: 43899

The relevant documentation is here:

You can directly use v-for on a custom component, like any normal element:

<my-component v-for="item in items" :key="item.id"></my-component>

In 2.2.0+, when using v-for with a component, a key is now required.

However, this won’t automatically pass any data to the component, because components have isolated scopes of their own. In order to pass the iterated data into the component, we should also use props:

   <my-component
     v-for="(item, index) in items"
     v-bind:item="item"
     v-bind:index="index"  
     v-bind:key="item.id">
   </my-component>

The reason for not automatically injecting item into the component is because that makes the component tightly coupled to how v-for works. Being explicit about where its data comes from makes the component reusable in other situations.

And here:

When Vue is updating a list of elements rendered with v-for, it by default uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will simply patch each element in-place and make sure it reflects what should be rendered at that particular index.

...

To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item. An ideal value for key would be the unique id of each item.

Upvotes: 1

euvl
euvl

Reputation: 4776

Use "key" attribute when rendering elements using v-for, for example:

<p v-for="(product, index) in order.products" :key="i">..</p>

Upvotes: 1

Related Questions