当前位置:首页 > 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 动态计算筛选结果,避免直接修改原始数据:

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>

优化性能

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

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实现网页切换

Vue 实现网页切换的方法 在 Vue 中实现网页切换通常可以通过以下几种方式完成,具体取决于项目需求和路由管理方式。 使用 Vue Router Vue Router 是 Vue.js 官方提供的…

vue实现sso

vue实现sso

Vue 实现 SSO(单点登录)方案 单点登录(SSO)允许用户通过一次登录访问多个相关系统。以下是基于 Vue 的实现方案: 使用 OAuth2/OpenID Connect 协议 OAuth2…

vue架构实现

vue架构实现

Vue 架构实现核心方案 Vue.js 的架构实现通常围绕模块化、组件化和状态管理展开。以下为常见实现方案: 基于单文件组件(SFC)的模块化 通过 .vue 文件组织模板、脚本和样式: &l…

vue实现文字

vue实现文字

Vue 中实现文字显示的方法 在 Vue 中实现文字显示可以通过多种方式,包括插值表达式、指令、组件等。以下是几种常见的实现方法: 插值表达式 使用双大括号 {{ }} 进行文本插值,这是 Vue…

vue实现翻译

vue实现翻译

Vue 实现翻译功能的方法 使用 i18n 插件实现多语言切换 安装 vue-i18n 插件: npm install vue-i18n 创建语言资源文件(如 en.json 和 zh.json):…

vue实现fadein

vue实现fadein

Vue 实现 FadeIn 效果 在 Vue 中实现淡入(FadeIn)效果可以通过 CSS 过渡、动画或第三方库实现。以下是几种常见方法: 使用 CSS 过渡 通过 Vue 的过渡系统结合 CSS…