vue商品模糊搜索
时间: 2023-07-11 18:10:31 浏览: 48
好的,以下是一个简单的Vue商品模糊搜索的示例代码:
1. 在你的Vue组件中,定义一个data属性,用于存储商品列表和搜索关键字:
```
data() {
return {
products: [], // 商品列表
searchKeyword: '' // 搜索关键字
}
}
```
2. 在模板中,使用v-model指令绑定搜索框的输入值,使用v-for指令遍历商品列表,显示每个商品的名称和价格:
```
<input type="text" v-model="searchKeyword" placeholder="请输入关键字">
<div v-for="(product, index) in filteredProducts" :key="index">
<p>{{ product.name }}</p>
<p>价格:{{ product.price }}</p>
</div>
```
3. 在Vue组件的computed中,定义filteredProducts计算属性,用于根据搜索关键字过滤商品列表:
```
computed: {
filteredProducts() {
return this.products.filter(product => {
return product.name.toLowerCase().indexOf(this.searchKeyword.toLowerCase()) !== -1
})
}
}
```
4. 在Vue组件的mounted生命周期钩子中,调用获取商品列表的API,并将返回的商品列表赋值给data属性中的products:
```
mounted() {
this.getProducts().then(products => {
this.products = products
})
},
methods: {
getProducts() {
// 调用获取商品列表的API
}
}
```
这样,当用户在搜索框中输入关键字时,Vue会自动根据关键字过滤商品列表,只显示名称中包含关键字的商品。