Vue: Unshift on array behaves in unexpected way when passing it as props

Created on 10 Jan 2017  ·  4Comments  ·  Source: vuejs/vue

Vue.js version

latest @ https://unpkg.com/vue/dist/vue.js v2.1.8

Reproduction Link

https://jsfiddle.net/ZimnyJS/jojhx7zq/2/

Steps to reproduce

Input any value in two text inputs and press unshift button, then change values in inputs and press unshift again.

What is Expected?

Recently inserted values should be prepended to the list.

What is actually happening?

Values from first submit are prepended to the list.

More description

Problem occurs when props passed via v-for is proxied to local data properties and then rendered.
Problem does not occur when push method is used to modify array.
Possible work-around is to add :key to v-for directive.

Most helpful comment

This is because you are not keying your components, so the child components are not re-ordered, they simply stay in the same position and receive new props. And because your child components only use the initial props, they do not update when receiving new props.

Either properly key the components, or just use the props directly so they update.

All 4 comments

In component x, you have set u and v to this.x and this.y in data function. ~So, these references are shared across all component instances.~

  1. Check console warnings
  2. <div>hello {{this.u}} / {{this.w}}</div> That is not correct way to access variables inside your template

Fixed your example - https://jsfiddle.net/740poaph/

thanks for quick action, regarding warnings in the console they are referring to main vue instance, not the component x itself. My code is based on http://vuejs.org/v2/guide/components.html#One-Way-Data-Flow which mentions:

Define a local data property that uses the prop’s initial value as its initial value:
props: ['initialCounter'],
data: function () {
return { counter: this.initialCounter }
}

it is a bit misleading.
Also can you please explain how is that different in case when push was used ?

same code without warnings https://jsfiddle.net/jojhx7zq/3/, following docs.

This is because you are not keying your components, so the child components are not re-ordered, they simply stay in the same position and receive new props. And because your child components only use the initial props, they do not update when receiving new props.

Either properly key the components, or just use the props directly so they update.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

seemsindie picture seemsindie  ·  3Comments

lmnsg picture lmnsg  ·  3Comments

guan6 picture guan6  ·  3Comments

aviggngyv picture aviggngyv  ·  3Comments

loki0609 picture loki0609  ·  3Comments