vue怎么实现搜索
Vue实现搜索功能的方法
在Vue中实现搜索功能通常涉及数据绑定、事件处理和列表过滤。以下是几种常见实现方式:
使用v-model和computed属性实现搜索
通过v-model绑定输入框,利用computed属性过滤数据:
<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用watch实现异步搜索
当需要从API获取搜索结果时,可以使用watch:
<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul v-if="results.length">
<li v-for="result in results" :key="result.id">
{{ result.title }}
</li>
</ul>
<p v-else>无搜索结果</p>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
results: [],
timer: null
}
},
watch: {
searchQuery(newVal) {
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.fetchResults(newVal)
}, 500)
}
},
methods: {
async fetchResults(query) {
if (!query.trim()) {
this.results = []
return
}
const response = await fetch(`/api/search?q=${query}`)
this.results = await response.json()
}
}
}
</script>
使用第三方库实现高级搜索
对于复杂搜索需求,可以使用Fuse.js等模糊搜索库:
<template>
<div>
<input v-model="searchTerm" placeholder="模糊搜索...">
<ul>
<li v-for="result in searchResults" :key="result.id">
{{ result.name }}
</li>
</ul>
</div>
</template>
<script>
import Fuse from 'fuse.js'
export default {
data() {
return {
searchTerm: '',
items: [
{ id: 1, name: 'JavaScript高级程序设计' },
{ id: 2, name: 'Vue.js实战' },
{ id: 3, name: 'React入门' }
],
fuse: null
}
},
computed: {
searchResults() {
return this.searchTerm
? this.fuse.search(this.searchTerm).map(r => r.item)
: this.items
}
},
mounted() {
this.fuse = new Fuse(this.items, {
keys: ['name'],
threshold: 0.4
})
}
}
</script>
实现搜索历史功能
可以添加搜索历史记录功能增强用户体验:
<template>
<div>
<input
v-model="searchInput"
@keyup.enter="performSearch"
placeholder="输入搜索内容..."
>
<button @click="performSearch">搜索</button>
<div v-if="searchHistory.length">
<h3>搜索历史</h3>
<ul>
<li
v-for="(term, index) in searchHistory"
:key="index"
@click="searchInput = term; performSearch()"
>
{{ term }}
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
searchInput: '',
searchHistory: []
}
},
methods: {
performSearch() {
if (!this.searchInput.trim()) return
// 添加到历史记录
if (!this.searchHistory.includes(this.searchInput)) {
this.searchHistory.unshift(this.searchInput)
// 限制历史记录数量
if (this.searchHistory.length > 5) {
this.searchHistory.pop()
}
}
// 执行搜索逻辑
console.log('搜索:', this.searchInput)
}
}
}
</script>
实现搜索高亮显示
在搜索结果中高亮显示匹配部分:
<template>
<div>
<input v-model="searchText" placeholder="搜索...">
<ul>
<li v-for="item in filteredItems" :key="item.id" v-html="highlight(item.text)"></li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchText: '',
items: [
{ id: 1, text: 'Vue是一款渐进式JavaScript框架' },
{ id: 2, text: 'React由Facebook开发' },
{ id: 3, text: 'Angular是Google的产品' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
this.searchText
? item.text.toLowerCase().includes(this.searchText.toLowerCase())
: true
)
}
},
methods: {
highlight(text) {
if (!this.searchText) return text
const regex = new RegExp(this.searchText, 'gi')
return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
以上方法可以根据具体需求选择或组合使用,实现从简单到复杂的各种搜索功能。







