JSFiddle - React, Tailwind, and code Playground
by inser
HTML
<div id="app" class="container">
<array-changer :arr="arr"></array-changer>
<hr />
<div v-for="a in arr" :key="a.index">
<b>{{ a }}</b>
</div>
<hr />
<array-display :arr="arr"></array-display>
</div>
Vue
var arrayChanger = {
props: ["arr"],
methods: {
addEl: function() {
this.arr.push({
index: this.arr.length,
value: Math.random(),
child: {
value: 'Child item value'
}
})
},
replaceEl: function() {
Vue.set(this.arr, 3, {index: 3, value: Math.random() })
// This will not work
//this.arr[3] = {index: 3, value: Math.random() }
}
},
template: `
<div>
<button @click="addEl">Add</button>
<button @click="replaceEl">replace 3rd</button>
</div>
`
};
var item = {
props: ["value"],
methods: {
changeItem: function () {
this.value.value = Math.random()
this.value.item.value = 'Child item (updated)'
}
},
template: `<div><div>{{value.index}} {{value.value}}</div> <a href="#" @click.prevent="changeItem">change</a></div>`
}
// Locally Registered Component
var arrayDisplay = {
props: ["arr"],
components: {
"v-item": item
},
methods: {
changeItem: function(item) {
item.value = Math.random()
}
},
template: `
<div class="local-component">
<div v-for="item in arr" :key="item.index">
<v-item v-model="item"></v-model>
</div>
</div>
`
};
// Vue Instance
new Vue({
el: "#app",
components: {
"array-display": arrayDisplay,
"array-changer": arrayChanger
},
data: function() {
return {
arr: []
}
},
});