<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
<button @click="deleteItem(item.id)">删除</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 4, name: 'Item 4' },
{ id: 5, name: 'Item 5' }
]
};
},
methods: {
deleteItem(itemId) {
this.items = this.items.filter(item => item.id !== itemId);
}
}
};
</script>
上面使用filter方法过滤掉items数组中id等于传入参数itemId的元素,并将过滤后的数组赋值给items属性