vue3实现搜索
Vue 3 实现搜索功能
在 Vue 3 中实现搜索功能通常涉及以下几个核心步骤:
数据绑定与输入监听
使用 v-model 绑定搜索输入框的值,监听用户输入:
<template>
<input v-model="searchQuery" placeholder="搜索..." />
</template>
<script setup>
import { ref } from 'vue';
const searchQuery = ref('');
</script>
过滤逻辑实现
基于输入内容过滤数据列表。如果是本地数据过滤:
const items = ref([/* 原始数据数组 */]);
const filteredItems = computed(() => {
return items.value.filter(item =>
item.name.toLowerCase().includes(searchQuery.value.toLowerCase())
);
});
如果是远程搜索,通常结合防抖优化性能:
import { debounce } from 'lodash-es';
const searchRemote = debounce(async () => {
const res = await fetch(`/api/search?q=${searchQuery.value}`);
filteredItems.value = await res.json();
}, 300);
watch(searchQuery, searchRemote);
结果展示
在模板中渲染过滤后的结果:
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
高级优化技巧
-
空状态处理:
<div v-if="filteredItems.length === 0">没有找到匹配项</div> -
高亮匹配文本:
const highlight = (text) => { const regex = new RegExp(searchQuery.value, 'gi'); return text.replace(regex, match => `<span class="highlight">${match}</span>`); }; -
多字段搜索:
const filteredItems = computed(() => { const query = searchQuery.value.toLowerCase(); return items.value.filter(item => ['name', 'description', 'tags'].some(field => String(item[field]).toLowerCase().includes(query) ) ); });
完整示例代码
<template>
<div>
<input v-model="searchQuery" placeholder="搜索..." />
<ul v-if="filteredItems.length">
<li v-for="item in filteredItems" :key="item.id">
<span v-html="highlight(item.name)"></span>
</li>
</ul>
<p v-else>没有搜索结果</p>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const searchQuery = ref('');
const items = ref([
{ id: 1, name: 'Vue.js' },
{ id: 2, name: 'React' },
{ id: 3, name: 'Angular' }
]);
const filteredItems = computed(() => {
const query = searchQuery.value.toLowerCase();
return query
? items.value.filter(item =>
item.name.toLowerCase().includes(query)
)
: items.value;
});
const highlight = (text) => {
const regex = new RegExp(searchQuery.value, 'gi');
return text.replace(regex, match => `<span class="highlight">${match}</span>`);
};
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
注意事项
- 对于大数据集考虑使用 Web Worker 进行后台过滤
- 移动端注意虚拟滚动优化性能
- 敏感字符输入需要进行转义处理防止 XSS 攻击
- 远程搜索建议添加加载状态和错误处理
通过以上方法可以构建出高效且用户友好的搜索功能,根据实际需求选择本地过滤或远程搜索方案。







