当前位置:首页 > 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

示例集成:

vue实现筛选列表

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

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

相关文章

vue实现中台

vue实现中台

Vue 实现中台系统的关键步骤 技术选型与基础搭建 使用 Vue 3(Composition API)或 Vue 2(Options API)作为前端框架,搭配 Vue Router 实现路由管理,V…

vue实现sso

vue实现sso

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

vue实现机制

vue实现机制

Vue 实现机制的核心原理 Vue.js 的核心实现机制主要基于响应式系统、虚拟 DOM 和组件化设计。以下是关键实现细节: 响应式系统 Vue 通过 Object.defineProperty(V…

vue 全景实现

vue 全景实现

Vue 全景实现方案 在Vue中实现全景效果,通常需要结合WebGL或第三方库来处理3D场景渲染。以下是几种常见方法: 使用Three.js库 Three.js是一个强大的WebGL库,适合创建3D…

vue实现频道

vue实现频道

Vue实现频道功能的方法 使用Vue Router动态路由 通过Vue Router的动态路由功能可以轻松实现频道切换。在路由配置中定义动态参数,组件内通过this.$route.params获取当前…

vue 实现跳转

vue 实现跳转

Vue 实现页面跳转的方法 在 Vue 中实现页面跳转通常可以通过以下几种方式实现,具体选择取决于项目需求和技术栈(如是否使用 Vue Router)。 使用 Vue Router 进行编程式导航…