Vue 中 filter 过滤的语法详解与注意事项
Vue 中 filter
过滤的语法详解与注意事项
在 Vue.js 中,"过滤"通常指两种不同概念:模板过滤器(Vue 2 特性)和数组过滤(数据过滤)。由于 Vue 3 已移除模板过滤器,我将重点介绍更实用且通用的数组过滤语法和注意事项。
一、数组过滤核心语法(推荐方式)
1. 使用计算属性(最佳实践)
computed: {filteredItems() {return this.items.filter(item => {// 过滤条件return item.name.includes(this.searchTerm) && item.price <= this.maxPrice;});}
}
2. 使用方法过滤(不推荐用于渲染)
methods: {filterItems(items) {return items.filter(item => item.isActive);}
}
3. 直接在模板中使用(性能最差)
<!-- 避免使用:每次渲染都会重新计算 -->
<div v-for="item in items.filter(i => i.stock > 0)">
二、关键注意事项
1. 性能优化(最重要)
- 优先使用计算属性:自动缓存结果,避免重复计算
- 避免在模板中直接过滤:每次渲染都会重新执行
- 大型数据集使用分页/虚拟滚动:
paginatedItems() {const start = (this.page - 1) * this.pageSize;return this.filteredItems.slice(start, start + this.pageSize); }
2. 空值处理
filteredItems() {// 确保 items 是数组const source = Array.isArray(this.items) ? this.items : [];return source.filter(item => {// 确保属性存在const name = item.name || '';return name.includes(this.searchTerm);});
}
3. 复杂过滤逻辑优化
computed: {filteredItems() {const { searchTerm, minPrice, category } = this.filters;return this.items.filter(item => {// 条件1:搜索词匹配const nameMatch = searchTerm ? item.name.toLowerCase().includes(searchTerm.toLowerCase()): true;// 条件2:价格范围const priceMatch = minPrice ? item.price >= minPrice : true;// 条件3:类别匹配const categoryMatch = category ? item.category === category : true;return nameMatch && priceMatch && categoryMatch;});}
}
4. 防抖处理(搜索场景)
data() {return {searchInput: '',searchTerm: '' // 实际用于过滤的值};
},
watch: {
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.dtcms.com/a/257952.html
如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!