如何不借助额外数组,基于Pinia原数组实现过滤与搜索?
解决方案:用计算属性实现动态过滤与搜索
完全可行,用计算属性结合Pinia的响应式状态就能实现,不需要额外维护过滤结果数组。核心思路是让计算属性依赖原数组、过滤条件和搜索关键词,动态返回处理后的结果。
1. 调整Pinia Store
只保留原数组状态,新增两个响应式变量存储过滤和搜索条件,去掉多余的filtersArray:
// stores/itemsStore.js import { defineStore } from 'pinia' export const useItemsStore = defineStore('items', { state: () => ({ items: [], // 原数组,通过fetch添加元素 activeFilterType: null, // 当前选中的过滤类型,null表示不过滤 searchKeyword: '' // 搜索框关键词 }), actions: { // 原有fetch添加元素的方法 async fetchItems() { const res = await fetch('your-api-url') const newItems = await res.json() this.items.push(...newItems) }, // 设置过滤类型(点击同类型时取消过滤) setFilterType(type) { this.activeFilterType = type === this.activeFilterType ? null : type }, // 更新搜索关键词 setSearchKeyword(keyword) { this.searchKeyword = keyword.trim() } } })
2. 组件中用计算属性处理过滤逻辑
在组件里定义计算属性,同时应用搜索和type过滤规则,直接渲染计算属性的结果:
<template> <div> <!-- 搜索输入框 --> <input type="text" placeholder="搜索内容..." v-model="searchKeyword" @input="store.setSearchKeyword($event.target.value)" /> <!-- 过滤按钮组 --> <button @click="store.setFilterType('type1')">类型1</button> <button @click="store.setFilterType('type2')">类型2</button> <button @click="store.setFilterType(null)" v-if="store.activeFilterType">取消过滤</button> <!-- 渲染过滤后的卡片 --> <div v-for="item in filteredItems" :key="item.id" class="card"> <h3>{{ item.title }}</h3> <p>类型:{{ item.type }}</p> <p>{{ item.description }}</p> </div> </div> </template> <script setup> import { useItemsStore } from '@/stores/itemsStore' import { computed } from 'vue' const store = useItemsStore() // 计算属性:动态生成过滤后的数组 const filteredItems = computed(() => { let processedItems = [...store.items] // 先执行搜索过滤 if (store.searchKeyword) { const lowerKeyword = store.searchKeyword.toLowerCase() processedItems = processedItems.filter(item => item.title.toLowerCase().includes(lowerKeyword) || item.description.toLowerCase().includes(lowerKeyword) ) } // 再执行类型过滤 if (store.activeFilterType) { processedItems = processedItems.filter(item => item.type === store.activeFilterType) } return processedItems }) // 初始化加载数据 store.fetchItems() </script>
核心优势
- 状态更简洁:无需维护额外的过滤结果数组,所有逻辑基于原数组和响应式条件
- 自动响应更新:计算属性会自动监听
items、activeFilterType、searchKeyword的变化,实时返回最新结果 - 逻辑灵活:可以自由调整搜索和过滤的先后顺序,也能快速扩展其他过滤规则
内容的提问来源于stack exchange,提问作者Jose
相关产品推荐
相关产品推荐

