使用 Array.prototype.findIndex() 方法查找与该 ID 匹配的项的索引。
使用 Vue.set() 方法替换该项。
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.id }} - {{ item.name }}
<button @click="replaceItem(item.id)">Replace</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' },
],
};
},
methods: {
replaceItem(id) {
const index = this.items.findIndex((item) => item.id === id);
if (index !== -1) {
const newItem = { id, name: `New Item ${id}` };
this.$set(this.items, index, newItem);
}
},
},
};
</script>