vue实现商品筛选
实现商品筛选功能
在Vue中实现商品筛选功能通常涉及以下几个关键步骤。以下是一个基于Vue 3的示例实现方式。
数据结构设计
商品数据通常以数组形式存储,每个商品对象包含属性如id、name、price、category等。示例数据结构如下:
const products = [
{ id: 1, name: '商品A', price: 100, category: '电子产品', stock: 10 },
{ id: 2, name: '商品B', price: 200, category: '服装', stock: 5 },
// 更多商品...
]
筛选条件管理
使用Vue的响应式数据来管理筛选条件:
const filters = reactive({
category: '',
priceRange: [0, 1000],
keyword: '',
inStock: false
})
计算筛选结果
使用计算属性实现筛选逻辑:
const filteredProducts = computed(() => {
return products.filter(product => {
const matchesCategory = !filters.category ||
product.category === filters.category
const matchesPrice = product.price >= filters.priceRange[0] &&
product.price <= filters.priceRange[1]
const matchesKeyword = !filters.keyword ||
product.name.toLowerCase().includes(filters.keyword.toLowerCase())
const matchesStock = !filters.inStock || product.stock > 0
return matchesCategory && matchesPrice && matchesKeyword && matchesStock
})
})
模板实现
在模板中绑定筛选条件和展示结果:
<div class="filter-controls">
<input v-model="filters.keyword" placeholder="搜索商品名称">
<select v-model="filters.category">
<option value="">所有分类</option>
<option v-for="cat in categories" :value="cat">{{ cat }}</option>
</select>
<label>
价格范围:
<input type="number" v-model.number="filters.priceRange[0]"> -
<input type="number" v-model.number="filters.priceRange[1]">
</label>
<label>
<input type="checkbox" v-model="filters.inStock"> 仅显示有货
</label>
</div>
<div class="product-list">
<div v-for="product in filteredProducts" :key="product.id" class="product">
<h3>{{ product.name }}</h3>
<p>价格: {{ product.price }}</p>
<p>分类: {{ product.category }}</p>
</div>
</div>
性能优化
对于大型商品列表,可以考虑以下优化措施:
使用防抖处理搜索输入:
const debouncedKeyword = ref('')
const updateDebouncedKeyword = debounce(() => {
debouncedKeyword.value = filters.keyword
}, 300)
watch(() => filters.keyword, updateDebouncedKeyword)
分页加载结果:
const paginatedProducts = computed(() => {
return filteredProducts.value.slice(
(currentPage.value - 1) * pageSize.value,
currentPage.value * pageSize.value
)
})
高级筛选功能
对于更复杂的筛选需求,可以:
实现多选分类筛选:
const filters = reactive({
selectedCategories: []
})
// 筛选逻辑调整为
const matchesCategory = filters.selectedCategories.length === 0 ||
filters.selectedCategories.includes(product.category)
添加排序功能:
const sortOptions = [
{ value: 'price-asc', text: '价格从低到高' },
{ value: 'price-desc', text: '价格从高到低' }
]
const sortedProducts = computed(() => {
const [field, order] = sortBy.value.split('-')
return [...filteredProducts.value].sort((a, b) => {
return order === 'asc' ? a[field] - b[field] : b[field] - a[field]
})
})
样式和交互增强
为提升用户体验,可以:
- 添加加载状态指示器
- 实现无结果时的友好提示
- 添加筛选条件的清除按钮
- 使用过渡动画使列表更新更平滑
<button @click="resetFilters">重置筛选条件</button>
<transition-group name="fade" tag="div">
<!-- 商品列表 -->
</transition-group>
以上实现方式可以根据具体项目需求进行调整和扩展,核心思路是通过Vue的响应式系统和计算属性来实现高效的商品筛选功能。







