1👍
Your problem is due to the main caveat of Vue reactivity system :
See working snippet below :
new Vue({
el: '#container',
data: {
value: [],
},
methods:{
updateValue(event){
this.$set(this.value, 1, [event.target.value])
}
},
beforeMount() {
this.value[0] = 'first level'
this.value[1] = []
this.value[1][0] = 'second level'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="container">
value[0] :
<input type="text" id="container" placeholder="enter text" v-model="value[0]">
<span>{{ value[0] }}</span>
<hr>
value[1][0] :
<input type="text" id="container" placeholder="enter text" @input="updateValue" :value="value[1][0]">
<span>{{ value[1][0] }}</span>
</div>
Note that if you try to do
updateValue(event){
this.value[1][0] = event.target.value
console.log(this.value[1][0]) //the value has changed but the UI is not refreshed
}
you will have the same problem : since what you’re doing is basically modifying one item inside your array (same goes for one property within the same object), meaning that your array is the same, Vue has no way to know your UI needs to be re-rendered.
Vue.$set
(or this.$set
) explicitly tells Vue that a data has been modified, forcing it to re-render corresponding DOM element.
$set
take three params : first is the object/array you want to update (this.value
), second is the index/property that needs to be modified (1
), third is the new value
It would also work if, instead of modifying one array item, you reassign the entire array :
updateValue(event){
this.value = [...this.value[0], [event.target.value]]
}