Vue.js 如何使用 v-for 和 v-if 过滤数组重复值
可以在 v-for 循环中使用一个变量来存储之前循环过的值,然后在每次循环时判断当前循环的值是否和之前的值重复,如果重复则跳过此次循环。
例如:
<div v-for='(item, index) in cp' v-if='!isDuplicate(item, index)'>
<!-- 显示数据 -->
</div>
然后在 Vue 实例中定义一个 isDuplicate 方法来判断是否重复:
data() {
return {
previousItems: []
}
},
methods: {
isDuplicate(item, index) {
if (this.previousItems.includes(item)) {
return true;
} else {
this.previousItems.push(item);
return false;
}
}
}
这样就可以通过 v-for 和 v-if 判断数组中是否有重复值,并跳过重复的数据。
原文地址: http://www.cveoy.top/t/topic/omJg 著作权归作者所有。请勿转载和采集!