vue实现搜素demo
以下是一个基于Vue实现的搜索功能Demo的完整方案,包含关键代码和实现逻辑:

基础组件结构
<template>
<div class="search-demo">
<input
v-model="searchQuery"
@input="handleSearch"
placeholder="输入搜索内容"
/>
<ul v-if="results.length">
<li v-for="item in results" :key="item.id">
{{ item.name }}
</li>
</ul>
<p v-else-if="searchQuery && !results.length">无匹配结果</p>
</div>
</template>
数据与逻辑实现
<script>
export default {
data() {
return {
searchQuery: '',
results: [],
allItems: [
{ id: 1, name: 'Vue基础教程' },
{ id: 2, name: 'React进阶指南' },
{ id: 3, name: 'JavaScript设计模式' }
]
}
},
methods: {
handleSearch() {
if (!this.searchQuery.trim()) {
this.results = []
return
}
const query = this.searchQuery.toLowerCase()
this.results = this.allItems.filter(item =>
item.name.toLowerCase().includes(query)
)
}
}
}
</script>
样式优化
<style scoped>
.search-demo {
max-width: 400px;
margin: 0 auto;
}
input {
width: 100%;
padding: 8px;
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>
高级功能扩展
添加防抖优化搜索性能:
import _ from 'lodash'
export default {
methods: {
handleSearch: _.debounce(function() {
// 原有搜索逻辑
}, 300)
}
}
实现异步API搜索:
methods: {
async handleSearch() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.results = response.data
} catch (error) {
console.error('搜索失败:', error)
}
}
}
功能增强建议
- 添加高亮匹配文本功能
- 实现搜索历史记录
- 增加结果分类筛选
- 添加加载状态指示器
- 支持键盘导航选择结果
这个Demo展示了Vue实现搜索功能的核心模式,可以根据实际需求进行扩展和优化。







