VueJS contains a great shorthand way of dealing with the oft-needed design of “send data down via props, emit changes up through events” principle: .sync
. If you use v-for
in conjunction with .sync
, though, there’s a sneaky “gotcha” that might waste a little bit of your time if you’re not aware of it ahead of time.
This certainly isn’t ground-breaking, but it’s a good thing to be aware of and keep in mind. In short, the “item” in a foreach loop is not a reference to the actual element in the array, and cannot be synced. So you might create something like this, and expect it to work.
It won’t! item
is not a reference to the actual array item, so while “item” will be synced with the child, myArray
will not. In this example, instead of:
<div v-for="item in myArray"> <my-component :text.sync='item'></my-component> </div>
You should use:
<div v-for="(item,index) in myArray"> <my-component :text.sync='myArray[index]'></my-component> </div>
Here’s a complete working version: