Reputation: 571
In vue.js, you can iterate over an array of items in your template like so:
<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>
Through experimentation, I also discovered you can do something similar with an object instead of an array:
<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 want to add to the array, you can do something like example2.items.push('four')
, and vue.js will react by inserting another DOM element. However, how would you go about inserting another item into an object instead in such a way that vue.js will react the same as it did to the array? You can't use the push method because it's not available to a generic object, so
I'm left trying something like:
example2.items.four = 'four'
But vue.js doesn't detect that change, so no new element is inserted into the DOM. My question is: How can i insert a new object ?
Upvotes: 0
Views: 138
Reputation: 571
Well, I asked too soon. I found the following documentation that answers my question. "Object Change Detection Caveats," found here: https://v2.vuejs.org/v2/guide/list.html
Upvotes: 0
Reputation: 2463
You have to use set
like this:
this.$set(this.myObject, 'newKey', { cool: 'its my new object' })
You could use Object.assign
too:
let newObject = { newKey: { cool: 'its my new object' }}
this.myObject = Object.assign({}, this.myObject, newObject)
More: https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats
Upvotes: 2