当前位置:首页 > VUE

vue实现筛选列表

2026-01-16 23:42:33VUE

Vue 实现筛选列表的方法

数据绑定与列表渲染

使用 v-for 指令渲染原始列表,绑定到 data 中的数组。例如:

data() {
  return {
    items: [
      { id: 1, name: 'Apple', category: 'Fruit' },
      { id: 2, name: 'Carrot', category: 'Vegetable' }
    ],
    filterText: '',
    filterCategory: ''
  }
}

模板中渲染列表:

<ul>
  <li v-for="item in filteredItems" :key="item.id">
    {{ item.name }} ({{ item.category }})
  </li>
</ul>

计算属性实现筛选逻辑

通过 computed 动态计算筛选结果,避免直接修改原始数据:

vue实现筛选列表

computed: {
  filteredItems() {
    return this.items.filter(item => {
      const matchesText = item.name.toLowerCase().includes(
        this.filterText.toLowerCase()
      );
      const matchesCategory = this.filterCategory === '' || 
        item.category === this.filterCategory;
      return matchesText && matchesCategory;
    });
  }
}

添加筛选交互控件

在模板中添加输入框和下拉菜单:

<input 
  type="text" 
  v-model="filterText" 
  placeholder="Search by name...">

<select v-model="filterCategory">
  <option value="">All Categories</option>
  <option value="Fruit">Fruit</option>
  <option value="Vegetable">Vegetable</option>
</select>

优化性能

对于大数据量场景,可添加防抖处理:

vue实现筛选列表

data() {
  return {
    debounceTimeout: null
  }
},
methods: {
  handleInput() {
    clearTimeout(this.debounceTimeout);
    this.debounceTimeout = setTimeout(() => {
      this.filterText = event.target.value;
    }, 300);
  }
}

多条件筛选扩展

支持更复杂的筛选条件时,可扩展计算属性:

computed: {
  filteredItems() {
    return this.items.filter(item => {
      // 多个条件组合
      return (
        (this.filterConditions.priceMin === '' || 
         item.price >= this.filterConditions.priceMin) &&
        (this.filterConditions.inStock || 
         !this.filterConditions.inStockOnly)
      );
    });
  }
}

使用第三方库

对于复杂需求,可考虑使用专用库:

npm install lodash.debounce vue-multiselect

示例集成:

import debounce from 'lodash.debounce';
export default {
  methods: {
    handleInput: debounce(function(e) {
      this.filterText = e.target.value;
    }, 300)
  }
}

标签: 列表vue
分享给朋友:

相关文章

vue手写签名如何实现

vue手写签名如何实现

实现手写签名的基本思路 在Vue中实现手写签名功能,通常需要借助HTML5的Canvas API来捕获用户的绘制操作。核心流程包括初始化画布、监听触摸/鼠标事件、记录轨迹以及生成签名图片。…

vue实现tablegrid

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue实现triger

vue实现triger

在Vue中实现触发器(trigger)功能通常涉及自定义事件或DOM事件触发。以下是几种常见场景的实现方法: 自定义事件触发 通过$emit方法触发父组件中监听的自定义事件: // 子组件 thi…

vue 实现注册

vue 实现注册

Vue 实现注册功能 注册功能通常包括表单验证、数据提交和用户反馈。以下是实现注册功能的步骤: 1. 创建注册表单组件 在 Vue 项目中创建一个注册表单组件,包含用户名、邮箱、密码等输入字段。…

vue mvvm 实现

vue mvvm 实现

Vue MVVM 实现原理 Vue.js 的 MVVM(Model-View-ViewModel)架构通过数据绑定和响应式系统实现视图与数据的自动同步。以下是其核心实现机制: 数据劫持与响应式系统…

vue实现popper

vue实现popper

Vue 实现 Popper 的方法 使用 Tippy.js 库 Tippy.js 是一个轻量级的 Popper.js 封装库,提供丰富的工具提示功能。安装 Tippy.js 及其 Vue 封装: n…