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: {
   

你可能感兴趣的:(Vue,vue.js,前端,javascript)