I have a Vue component and a root Vue instance. The instance contains an array of objects (for products) and the component is displayed in my HTML using a v-for loop for each product. This is what products.js looks like:
/**
* Component to show products
*/
Vue.component('product', {
props: ['product'],
data: function() {
return {
localProduct: this.product
};
},
template: `<div class="products">
<span>{{ localProduct.product }}</span>
<a href="javascript:void" v-on:click="remove">Remove</a>
</div>`,
methods: {
remove: function() {
var removeIndex = productsList.products.map(function(i) { return i.id; }).indexOf(this.localProduct.id);
productsList.products.splice(removeIndex, 1);
}
}
});
/**
* Instantiate root Vue instance
*/
var productsList = new Vue({
el: '#products',
data: {
products: [{ id: 1, product: 'iPad' }, { id: 2, product: 'iPhone' }, { id: '3', product: 'AirPods' }]
}
});
Now, the loop renders 3 DIVs for iPad, iPhone and AirPods. What's strange is, when I click the remove button for iPhone (productsList.products[1]), the HTML displays iPad and iPhone instead of iPad and AirPods (since we removed iPhone). I just can't figure out what's going on.
My array splice code seems to be working correctly as well. I console.logged the updated array after the splice function and it only included iPad and AirPods (correct) but strangely, the view is different! Can someone tell me what I'm doing wrong here? Thanks.