Filipe Picoito
Filipe Picoito

Reputation: 695

Vue foreach not filtering correctly

I've been trying Vue 1.x and I've just recently switched over to 2.x and I've been slowly modifying some stuff, mainly directives.

Right now I'm struggling with a filtering of an array. Imagine that I have 3 items, A, B and C. No matter which one I say is being filtered out, it's always the last element that appears. So imagine I delete A, then C will dissapear.

I've created a jsFiddle as an example: https://jsfiddle.net/arj70sz4/

As required by StackOverflow:

for-each code from HTML:

<foo-single
  v-for="foo in foos"
  v-bind:foo="foo"
>
</foo-single>

filtering code from JS:

this.foos = this.foos.filter(function (v) {
  return foo.id != v.id;
});

I know there is another way to do this filtering, by splicing the array, but that way the same result was occurring.

Could someone enlighten me? I feel as if my mistake is actually pretty dumb but I can't seem to figure it out right now.

Upvotes: 1

Views: 1861

Answers (1)

Saurabh
Saurabh

Reputation: 73649

You just need to add key in v-for

<foo-single v-for="foo in foos" v-bind:foo="foo" :key="foo.id">
</foo-single>

For the improvement of performance, v-for uses an “in-place patch” strategy and list rendering will not change on child component state or temporary DOM state changes. To track these changes you need to add key attribute with v-for.

See working fiddle here.

Upvotes: 2

Related Questions