Vue如何基于form-select选择值过滤设备列表,避免v-if与v-for共用
实现方案
Vue官方不推荐v-if与v-for同用的核心原因是v-for优先级更高,会先遍历所有元素再做判断,浪费渲染性能,你可以通过计算属性预过滤设备数组的方式实现需求,修改步骤如下:
- 在你的Vue组件中新增
filteredDevices计算属性,根据选中的筛选项动态返回过滤后的设备列表:
import { devices, options } from '../devices' export default { data() { return { devices: devices, options: options, selected: 'All', }; }, // 新增以下计算属性代码 computed: { filteredDevices() { switch(this.selected) { case 'All': return this.devices case 'Active': case 'Deactive': return this.devices.filter(item => item.status === this.selected) // 后续如果要实现Traffic、Location的过滤逻辑,直接加case即可 default: return this.devices } } } };
- 修改模板中v-for的遍历源,把原来的
devices替换为计算属性filteredDevices,其余模板代码无需改动:
<tr v-for="device in filteredDevices" :key="device.id"> <!-- 此处保持你原有的td渲染逻辑不变 --> </tr>
这种方案利用了Vue计算属性的缓存特性,只有当selected筛选项或者原devices数组发生变化时,才会重新执行过滤逻辑,性能远高于v-if和v-for同用的写法,也符合Vue的官方编码规范。
内容的提问来源于stack exchange,提问作者Yasin Demirkaya
相关产品推荐
相关产品推荐

