If there are some components inside loop, when I remove a component data, the UI works expected, but in beforeDestroy(), it always get last component property value.
You can test it in fiddle https://jsfiddle.net/robedgenius/817komr8/. When clicking "remove" button, it removes data index "1". However, the beforeDestroy method alert message is "4", i.e, the last index.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.1/vue.min.js"></script>
<div id="main">
<div>
<button @click.prevent="destoryEle(1)">Remove</button>
</div>
<template v-for="g in gridData">
<demo-grid :aid="g.aid" :name="g.name" :power="g.power"></demo-grid>
</template>
<br/>end
</div>
<script type="text/x-template" id="grid-template">
<div>
<span v-text="aid"></span>: <span v-text="name"></span> - <span v-text="power"></span>
</div>
</script>
Javascript code here:
Vue.component('demo-grid', {
template: '#grid-template',
replace: true,
props: {
aid: 0,
name: Object,
power: Object,
},
beforeDestroy (){
alert('destroy: ' + this.aid);
}
});
// Creating a new Vue instance and pass in an options object.
var demo = new Vue({
// A DOM element to mount our view model.
el: '#main',
// Define properties and give them initial values.
data: {
gridData: [
{aid: 1, name: 'Chuck Norris', power: Infinity },
{aid: 2, name: 'Bruce Lee', power: 9000 },
{aid: 3, name: 'Jackie Chan', power: 7000 },
{aid: 4, name: 'Jet Li', power: 8000 }
]
},
methods:{
destoryEle: function(aid){
this.gridData.splice(aid, 1);
}
}
});
When you iterate components with v-for, you need to provide a key. Otherwise Vue 2 implicitly keys them by index, and the instance that actually dies is in fact the last one in the list. Unless your instances are stateless, this causes issues like the one you describe.
Most helpful comment
When you iterate components with
v-for, you need to provide akey. Otherwise Vue 2 implicitly keys them by index, and the instance that actually dies is in fact the last one in the list. Unless your instances are stateless, this causes issues like the one you describe.Demo: https://jsfiddle.net/817komr8/2/