Vue 循环修改对象数组属性:使用 map 方法示例
<template>
<div>
<ul>
<li v-for='(item, index) in items' :key='item.id'>
{{ item.name }} - {{ item.quantity }}
<button @click='increaseQuantity(index)'>增加数量</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '苹果', quantity: 5 },
{ id: 2, name: '香蕉', quantity: 3 },
{ id: 3, name: '橙子', quantity: 2 }
]
}
},
methods: {
increaseQuantity(index) {
this.items = this.items.map((item, i) => {
if (i === index) {
return { ...item, quantity: item.quantity + 1 };
}
return item;
});
}
}
}
</script>
<p>在上面的示例中,使用 <code>v-for</code> 指令遍历 <code>items</code> 数组,并通过 <code>item</code> 和 <code>index</code> 获取每个对象的属性和索引。点击按钮时,调用 <code>increaseQuantity</code> 方法来增加对应对象的 <code>quantity</code> 属性值。这样就能循环修改对象数组的某一个属性。</p>
<p>使用 <code>map</code> 方法改进上面的示例:</p>
<p>在改进后的方法中,使用 <code>map</code> 方法遍历 <code>items</code> 数组,并根据索引判断是否需要修改对应的属性值。如果索引匹配,则返回一个新的对象,其中 <code>quantity</code> 属性值加 1;否则,返回原始对象。通过这种方式,我们可以实现循环修改对象数组的某一个属性。</p>
原文地址: https://www.cveoy.top/t/topic/p51d 著作权归作者所有。请勿转载和采集!