vue实现搜素demo
以下是一个基于Vue的搜索功能实现示例,包含关键代码和逻辑说明:
基础实现
创建Vue组件模板部分:
<template>
<div>
<input
v-model="searchQuery"
@input="handleSearch"
placeholder="输入关键词..."
/>
<ul v-if="filteredItems.length">
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<p v-else>无匹配结果</p>
</div>
</template>
数据与逻辑处理
JavaScript部分实现搜索过滤:
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
],
filteredItems: []
}
},
methods: {
handleSearch() {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
},
created() {
this.filteredItems = [...this.items]
}
}
优化版本(防抖处理)
添加性能优化防止频繁触发搜索:
import { debounce } from 'lodash'
export default {
methods: {
handleSearch: debounce(function() {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}, 300)
}
}
异步搜索实现
对接API的异步搜索方案:
export default {
methods: {
async handleSearch() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.filteredItems = response.data
} catch (error) {
console.error('搜索出错:', error)
}
}
}
}
样式增强
添加基础样式改善视觉效果:
<style scoped>
input {
padding: 8px;
width: 300px;
border: 1px solid #ddd;
border-radius: 4px;
}
ul {
list-style: none;
padding: 0;
margin-top: 10px;
}
li {
padding: 8px;
border-bottom: 1px solid #eee;
}
</style>
可根据实际需求调整搜索算法(如模糊搜索、拼音搜索等)或添加更多功能如高亮匹配文本、搜索历史记录等。







