vue实现产品搜索
实现产品搜索功能
在Vue中实现产品搜索功能可以通过以下步骤完成。假设有一个产品列表,用户可以通过输入关键词来筛选产品。
1. 准备数据 创建一个产品数组,包含产品的基本信息如名称、描述、价格等。
data() {
return {
products: [
{ id: 1, name: '手机', description: '高性能智能手机', price: 2999 },
{ id: 2, name: '笔记本电脑', description: '轻薄便携', price: 5999 },
{ id: 3, name: '耳机', description: '无线降噪耳机', price: 999 }
],
searchQuery: ''
}
}
2. 创建搜索输入框
在模板中添加一个输入框,用于接收用户的搜索关键词。使用v-model双向绑定到searchQuery。
<template>
<div>
<input v-model="searchQuery" placeholder="搜索产品..." />
<ul>
<li v-for="product in filteredProducts" :key="product.id">
{{ product.name }} - {{ product.description }} - ¥{{ product.price }}
</li>
</ul>
</div>
</template>
3. 计算筛选后的产品列表
使用computed属性根据searchQuery动态筛选产品。这里对产品名称和描述进行不区分大小写的匹配。

computed: {
filteredProducts() {
const query = this.searchQuery.toLowerCase()
return this.products.filter(product => {
return (
product.name.toLowerCase().includes(query) ||
product.description.toLowerCase().includes(query)
)
})
}
}
4. 添加样式和交互优化 可以添加一些CSS样式美化搜索框和产品列表。对于大型数据集,考虑添加防抖功能减少频繁搜索带来的性能问题。
methods: {
debounceSearch: _.debounce(function() {
this.filteredProducts()
}, 300)
}
高级搜索功能实现
对于更复杂的需求,可以扩展搜索功能:

多条件搜索 添加多个搜索字段,如价格范围、类别等。在计算属性中组合这些条件进行筛选。
data() {
return {
priceRange: [0, 10000],
category: ''
}
},
computed: {
filteredProducts() {
return this.products.filter(product => {
const matchesSearch = product.name.toLowerCase().includes(this.searchQuery.toLowerCase())
const matchesPrice = product.price >= this.priceRange[0] && product.price <= this.priceRange[1]
const matchesCategory = this.category ? product.category === this.category : true
return matchesSearch && matchesPrice && matchesCategory
})
}
}
远程搜索 当产品数据量很大时,可以改为从API获取搜索结果:
methods: {
async searchProducts() {
const response = await axios.get('/api/products', {
params: {
q: this.searchQuery,
minPrice: this.priceRange[0],
maxPrice: this.priceRange[1]
}
})
this.filteredProducts = response.data
}
}
性能优化建议
对于大型产品列表,虚拟滚动可以提高渲染性能。使用vue-virtual-scroller等库只渲染可见区域的产品项。
import { RecycleScroller } from 'vue-virtual-scroller'
components: {
RecycleScroller
}
<RecycleScroller
class="scroller"
:items="filteredProducts"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<div class="product-item">
{{ item.name }}
</div>
</template>
</RecycleScroller>






