vue怎么实现搜索功能
实现搜索功能的方法
在Vue中实现搜索功能可以通过多种方式完成,以下是一些常见的方法:
使用计算属性实现搜索 计算属性可以根据输入的关键词实时过滤数据,适合简单的搜索场景。
<template>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredItems" :key="item.id">{{ item.name }}</li>
</ul>
</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监听搜索词变化 当搜索需要更复杂的逻辑或异步操作时,可以使用watch监听搜索词变化。
<script>
export default {
data() {
return {
searchQuery: '',
filteredItems: [],
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
watch: {
searchQuery(newVal) {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(newVal.toLowerCase())
)
}
},
created() {
this.filteredItems = [...this.items]
}
}
</script>
使用第三方库实现高级搜索 对于更复杂的搜索需求,可以使用如Fuse.js这样的模糊搜索库。
import Fuse from 'fuse.js'
<script>
export default {
data() {
return {
searchQuery: '',
fuse: null,
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
],
searchResults: []
}
},
created() {
this.fuse = new Fuse(this.items, {
keys: ['name'],
threshold: 0.4
})
},
watch: {
searchQuery(newVal) {
this.searchResults = newVal ?
this.fuse.search(newVal).map(r => r.item) :
[...this.items]
}
}
}
</script>
与后端API结合实现搜索 当数据量较大时,通常需要将搜索请求发送到后端处理。
<script>
export default {
data() {
return {
searchQuery: '',
searchResults: [],
timeout: null
}
},
methods: {
searchItems() {
clearTimeout(this.timeout)
this.timeout = setTimeout(async () => {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.searchResults = response.data
} catch (error) {
console.error('搜索出错:', error)
}
}, 500)
}
},
watch: {
searchQuery() {
this.searchItems()
}
}
}
</script>
添加搜索防抖优化性能 对于频繁触发的搜索输入,添加防抖可以优化性能。
<script>
import { debounce } from 'lodash'
export default {
data() {
return {
searchQuery: '',
filteredItems: []
}
},
created() {
this.debouncedSearch = debounce(this.performSearch, 300)
},
methods: {
performSearch() {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
},
watch: {
searchQuery() {
this.debouncedSearch()
}
}
}
</script>
以上方法可以根据具体需求选择使用,简单搜索可以使用计算属性,复杂搜索可以考虑使用第三方库或结合后端API实现。







