vue实现搜索产品列表
Vue 实现搜索产品列表
数据准备
在Vue组件的data中定义产品列表和搜索关键词。产品列表可以是从API获取或本地定义的数据。
data() {
return {
products: [
{ id: 1, name: '产品A', price: 100 },
{ id: 2, name: '产品B', price: 200 },
{ id: 3, name: '产品C', price: 300 }
],
searchQuery: ''
}
}
计算属性过滤
使用计算属性根据搜索关键词过滤产品列表。计算属性会自动更新,无需手动触发。
computed: {
filteredProducts() {
return this.products.filter(product =>
product.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
模板绑定
在模板中绑定搜索输入框和过滤后的产品列表。使用v-model实现双向绑定。
<template>
<div>
<input v-model="searchQuery" placeholder="搜索产品...">
<ul>
<li v-for="product in filteredProducts" :key="product.id">
{{ product.name }} - {{ product.price }}
</li>
</ul>
</div>
</template>
样式优化
添加基本样式提升用户体验。例如为搜索框和列表添加间距和边框。
input {
padding: 8px;
margin-bottom: 16px;
width: 200px;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 8px;
border: 1px solid #eee;
margin-bottom: 4px;
}
异步数据加载
如果产品数据需要从API异步获取,可以在created或mounted钩子中调用方法。
methods: {
fetchProducts() {
// 模拟API调用
setTimeout(() => {
this.products = [
{ id: 4, name: '产品D', price: 400 },
{ id: 5, name: '产品E', price: 500 }
]
}, 1000)
}
},
created() {
this.fetchProducts()
}
性能优化
对于大型列表,考虑添加防抖或分页功能。使用lodash的debounce方法可以限制搜索频率。
import { debounce } from 'lodash'
methods: {
search: debounce(function() {
// 搜索逻辑
}, 500)
}






