When using vue.js, you have the ability to iterate over an array of items in your template as shown below:
<div id="app">
<div v-for="(item, i) in items">i: item</div>
</div>
<script>
var example2 = new Vue({
el: '#app',
data: {
items: ['one', 'two', 'three']
}
})
</script>
In my exploration, I found that a similar approach can be taken with objects instead of arrays:
<div id="app">
<div v-for="(item, i) in items">i: item</div>
</div>
<script>
var example2 = new Vue({
el: '#app',
data: {
items: {one: 'one', two: 'two', three: 'three'}
}
})
</script>
If you need to add an element to the array, you can use example2.items.push('four')
, and vue.js will update the DOM accordingly. However, adding a new item to an object is not as straightforward since the push method does not work with generic objects. One way to try this is by doing the following:
example2.items.four = 'four'
Unfortunately, vue.js does not detect this change and doesn't insert a new element into the DOM. So, the question arises: How can I insert a new object?