I have seen multiple examples where indexOf
is used within Vue to select an object from an array of objects like this:
Script:
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
items: [
{
id: 1,
name: 'test'
},
{
id: 2,
name: 'hello'
},
{
id: 3,
name: 'world'
}
]
},
methods: {
deleteItem(item) {
console.log(this.items.indexOf(item));
// splice the item.
}
}
})
Template:
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p>{{ message }}</p>
<ul>
<li v-for="item in items" @click=deleteItem(item)>
{{ item.name }}
</li>
</ul>
</div>
https://jsfiddle.net/5gwtyv3h/
Now I am wondering this is even possible. If I go into my console and simply do this:
const items = [
{
id: 1,
name: 'test'
},
{
id: 2,
name: 'hello'
},
{
id: 3,
name: 'world'
}
];
items.indexOf({ id: 1, name: 'test'});
I get -1 because the item can not be found. Is Vue doing something that makes this possible or I missing something else here?