Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 编程脚本 / 在 Vue 3 中,利用数组的 filter 方法配合箭头函数是最直接、高效且语义清晰的解决方案。

在 Vue 3 中,利用数组的 filter 方法配合箭头函数是最直接、高效且语义清晰的解决方案。
核心方案
使用 Array.prototype.filter 方法,遍历 tableDataSource.value,保留那些 id 属性存在于 selectedProducts.value 数组中的对象。
1. 基础写法(推荐)
// 假设
// const tableDataSource = reactive([
//   { id: 1, name: 'Apple' },
//   { id: 2, name: 'Banana' },
//   { id: 3, name: 'Cherry' }
// ]);
// const selectedProducts = reactive([1, 3]);
// 快速筛选
const filteredList = tableDataSource.value.filter(item => 
 selectedProducts.value.includes(item.id)
);
console.log(filteredList); 
// 输出: [{ id: 1, name: 'Apple' }, { id: 3, name: 'Cherry' }]
代码解析:
tableDataSource.value.filter(...): 遍历主列表。
selectedProducts.value.includes(item.id): 检查当前对象的 id 是否存在于 ID 数组中。如果存在返回 true,该对象就会被保留。
注意:includes 是 ES6 新增方法,性能足以应对绝大多数前端场景(通常数据量在几万条以内无压力)。
2. 性能优化版(数据量大时)
如果 tableDataSource 数据量非常大(例如超过 10 万行)或者 selectedProducts 更新非常频繁,includes 的时间复杂度是 O(n),会导致整体过滤变慢。此时建议先将 ID 数组转换为 Set 或 Map,将查找复杂度降低到 O(1)。

// 优化方案:将 ID 数组转为 Set
const idSet = new Set(selectedProducts.value);
const optimizedFilteredList = tableDataSource.value.filter(item => 
 idSet.has(item.id)
);
// 如果需要在模板中动态使用,可以将其存入响应式引用
watch([tableDataSource, selectedProducts], ([newSource, newSelected], [, oldSelected], { deep }) => {
 if (oldSelected) { // 仅在数据变化时计算,避免重复计算
 // 创建 Set (每次更新时)
 const currentIds = new Set(newSelected.value);
 // 过滤
 value.value = newSource.value.filter(item => currentIds.has(item.id));
 }
}, { deep: true });
3. 在 Vue 模板 (Template) 中的用法
如果你是在 .vue 文件的 <script setup> 外部或模板中直接使用计算属性(Computed),Vue 会自动处理响应性,无需手动调用 .value(除非是在 script 标签内的逻辑)。
方案 A:使用计算属性(最常用)
import { computed } from 'vue';
// ...
// 在 script setup 中定义数据
const tableDataSource = ref([...]);
const selectedProducts = ref([1, 3]);
// 定义计算属性
const filteredList = computed(() => {
 return tableDataSource.value.filter(item => 
 selectedProducts.value.includes(item.id)
 );
});

总结
日常使用:直接使用 array.filter(item => ids.includes(item.id)) 即可。
高性能场景:先将 ID 数组转为 Set,然后使用 set.has() 判断。
响应式处理:在模板中使用时,通常建议将过滤逻辑封装在 computed 属性中,以确保性能优化和代码整洁