In Vue, the item self-reference can be used in many different ways to perform various operations on an item in a list. Here are a few examples:
<template>
<div v-for="(item, index) in items" :key="index">
<input type="text" v-model="item.name">
</div>
</template>
In this example, we have a list of items and we want to allow the user to update the name of each item. We use v-model
to bind the name
property of the current item to the text input, so that any changes made by the user will be reflected in the data.
<template>
<div v-for="(item, index) in items" :key="index">
<button @click="deleteItem(item)">Delete</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
],
};
},
methods: {
deleteItem(item) {
const index = this.items.indexOf(item);
this.items.splice(index, 1);
},
},
};
</script>
In this example, we have a list of items and a button for each item that, when clicked, should delete that item from the list. We use the deleteItem
method to remove the item from the items
array by finding its index and using splice
to remove it.
<template>
<div v-for="(item, index) in filteredItems" :key="index">
<p>{{ item.name }}</p>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1', category: 'A' },
{ id: 2, name: 'Item 2', category: 'B' },
{ id: 3, name: 'Item 3', category: 'A' },
],
filterCategory: 'A',
};
},
computed: {
filteredItems() {
return this.items.filter(item => item.category === this.filterCategory);
},
},
};
</script>
In this example, we have a list of items and we want to display only the items that belong to a certain category. We use a computed property filteredItems
to filter the items
array based on the category
property of each item. The filterCategory
value can be updated to change which items are shown.
Asked: 2021-11-24 11:00:00 +0000
Seen: 1 times
Last updated: Aug 02 '22