vue实现input模糊搜索
Vue 实现 input 模糊搜索
基本实现思路
在 Vue 中实现 input 模糊搜索通常需要以下几个步骤:监听输入框变化、过滤数据列表、展示搜索结果。以下是一个完整的实现示例。
代码实现
<template>
<div>
<input
v-model="searchQuery"
placeholder="输入关键词搜索"
@input="handleSearch"
/>
<ul v-if="filteredItems.length">
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<p v-else>暂无结果</p>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
],
filteredItems: []
}
},
methods: {
handleSearch() {
if (!this.searchQuery) {
this.filteredItems = this.items;
return;
}
const query = this.searchQuery.toLowerCase();
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(query)
);
}
},
created() {
this.filteredItems = this.items;
}
}
</script>
关键点解析
- v-model双向绑定:通过
v-model将输入框的值与searchQuery数据绑定。 - @input事件监听:输入时触发
handleSearch方法。 - 数组过滤:使用
filter和includes方法实现模糊匹配。 - 大小写处理:统一转为小写避免大小写敏感问题。
优化方向
-
防抖处理:频繁输入时使用防抖减少计算次数。
import { debounce } from 'lodash'; methods: { handleSearch: debounce(function() { // 搜索逻辑 }, 300) } -
高亮匹配文本:使用正则表达式实现搜索词高亮。
<li v-for="item in filteredItems" :key="item.id"> <span v-html="highlight(item.name, searchQuery)"/> </li>methods: { highlight(text, query) { return query ? text.replace(new RegExp(query, 'gi'), match => `<mark>${match}</mark>`) : text; } } -
异步搜索:当数据量较大时改用后端接口搜索。
完整组件示例
// SearchComponent.vue
<template>
<div class="search-box">
<input
v-model.trim="searchQuery"
class="search-input"
placeholder="输入关键词..."
/>
<transition-group name="fade" tag="ul" class="results">
<li v-for="result in results" :key="result.id" @click="selectItem(result)">
{{ result.text }}
</li>
</transition-group>
</div>
</template>
<script>
export default {
props: {
sourceData: Array
},
data() {
return {
searchQuery: '',
results: []
}
},
watch: {
searchQuery(newVal) {
this.search(newVal)
}
},
methods: {
search(query) {
this.results = query
? this.sourceData.filter(item =>
item.text.toLowerCase().includes(query.toLowerCase())
)
: []
},
selectItem(item) {
this.$emit('selected', item)
this.searchQuery = ''
this.results = []
}
}
}
</script>
<style>
.search-box {
position: relative;
}
.results {
position: absolute;
width: 100%;
}
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
使用注意事项
- 对于大型数据集建议采用分页加载
- 移动端需要额外处理虚拟键盘事件
- 可添加无结果时的默认提示或推荐内容
通过以上方式可以构建一个功能完整的模糊搜索组件,根据实际需求可进一步扩展功能。







