当前位置:首页 > VUE

vue实现点击筛选

2026-03-28 18:27:43VUE

实现点击筛选功能

在Vue中实现点击筛选功能可以通过以下步骤完成:

  1. 准备数据 创建需要筛选的数据数组和筛选条件变量。
data() {
  return {
    items: [
      { id: 1, name: 'Apple', category: 'fruit' },
      { id: 2, name: 'Carrot', category: 'vegetable' },
      { id: 3, name: 'Banana', category: 'fruit' }
    ],
    selectedCategory: 'all'
  }
}
  1. 创建筛选方法 添加计算属性来处理筛选逻辑。
computed: {
  filteredItems() {
    if (this.selectedCategory === 'all') {
      return this.items
    }
    return this.items.filter(item => item.category === this.selectedCategory)
  }
}
  1. 创建筛选按钮 在模板中添加筛选按钮并绑定点击事件。
<div>
  <button @click="selectedCategory = 'all'">All</button>
  <button @click="selectedCategory = 'fruit'">Fruits</button>
  <button @click="selectedCategory = 'vegetable'">Vegetables</button>
</div>
  1. 显示筛选结果 使用v-for指令显示筛选后的结果。
<ul>
  <li v-for="item in filteredItems" :key="item.id">
    {{ item.name }} ({{ item.category }})
  </li>
</ul>

动态筛选选项实现

如果需要动态生成筛选按钮:

data() {
  return {
    // ...其他数据
    categories: ['all', 'fruit', 'vegetable']
  }
}
<div>
  <button 
    v-for="category in categories" 
    :key="category"
    @click="selectedCategory = category"
  >
    {{ category }}
  </button>
</div>

添加样式反馈

为当前选中的筛选按钮添加样式反馈:

<button 
  v-for="category in categories" 
  :key="category"
  @click="selectedCategory = category"
  :class="{ active: selectedCategory === category }"
>
  {{ category }}
</button>
.active {
  background-color: #42b983;
  color: white;
}

多条件筛选实现

如果需要实现多条件筛选:

vue实现点击筛选

data() {
  return {
    filters: {
      category: 'all',
      priceRange: 'all'
    }
  }
},
computed: {
  filteredItems() {
    return this.items.filter(item => {
      const categoryMatch = this.filters.category === 'all' || 
                          item.category === this.filters.category
      const priceMatch = this.filters.priceRange === 'all' || 
                        this.checkPriceRange(item.price)
      return categoryMatch && priceMatch
    })
  }
}

标签: vue
分享给朋友:

相关文章

vue computed 实现

vue computed 实现

computed 的基本用法 在 Vue 中,computed 用于声明计算属性,这些属性基于响应式依赖进行缓存。只有当依赖发生变化时,计算属性才会重新计算。 new Vue({ data: {…

vue实现input

vue实现input

Vue 实现 Input 输入框的方法 基本双向绑定 使用 v-model 指令实现双向数据绑定,适用于大多数表单场景: <template> <input v-model="…

vue实现抽奖

vue实现抽奖

Vue 实现抽奖功能 基本抽奖逻辑 创建一个Vue组件,包含奖品列表、抽奖按钮和结果显示区域。使用随机数生成器选择奖品。 <template> <div> <…

vue实现网站

vue实现网站

Vue 实现网站的基本步骤 Vue.js 是一个渐进式 JavaScript 框架,适合构建现代化的单页应用(SPA)或动态网站。以下是使用 Vue 实现网站的基本方法。 初始化 Vue 项目 使用…

vue实现tooltips

vue实现tooltips

Vue 实现 Tooltips 的方法 使用原生 HTML title 属性 在 Vue 模板中直接使用 HTML 原生 title 属性实现简单的提示效果。这种方式无需额外依赖,但功能较为基础,无法…

vue实现销售程序

vue实现销售程序

Vue实现销售程序的基本步骤 搭建Vue项目基础结构 使用Vue CLI或Vite初始化项目,安装必要依赖(如Vue Router、Vuex/Pinia、Element UI/Ant Design V…