So I've been using vuejs for a few months and I couldn't understand what is happening here. I did this I modified the vuejs code in list rendering for a bit
html:
<ul id="array-with-index" class="demo">
<li v-for="(item, index) of items" :key = "index">
{{ parentMessage }} - {{ index }} - {{ item.message }}
<button @click = "removeItem(index)"> remove </button>
</li>
<button @click = "addItem"> add </button>
</ul>
And this is the code in javascript:
Vue.createApp({
data() {
return {
parentMessage: 'Parent',
items: [{ message: 'Foo' }, { message: 'Bar' }]
}
},
methods: {
removeItem(index){
this.items.splice(index, 1);
},
addItem(){
this.items.push({message: "hello"});
}
}
}).mount('#array-with-index')
Every time I pushed a few new item in items and decided I would delete the item before the last item. It deletes the last item instead. Why does this happen? and how can I remedy this?
for...ininstead offor...of[ Compute property is a reactive function and that means if one of its dependencies change, it'll change as well. Otherwise, it won't [ Optimization manner ]indexfor the unique keys. More info