vue实现前端搜索
实现前端搜索功能的方法
使用计算属性实现搜索
在Vue中可以利用计算属性对数据进行过滤,实现搜索功能。计算属性会根据依赖的数据自动更新,适合处理搜索逻辑。
<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和methods实现搜索
对于更复杂的搜索逻辑,可以使用watch配合methods来实现,这种方式在处理大量数据或需要异步搜索时更有优势。

<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in searchResults" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
searchResults: [],
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
watch: {
searchQuery(newVal) {
this.performSearch(newVal)
}
},
methods: {
performSearch(query) {
this.searchResults = this.items.filter(item =>
item.name.toLowerCase().includes(query.toLowerCase())
)
}
}
}
</script>
使用第三方库实现高级搜索
对于更复杂的搜索需求,可以考虑使用第三方库如Fuse.js,它提供了模糊搜索、权重设置等高级功能。

import Fuse from 'fuse.js'
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果', category: '水果' },
{ id: 2, name: '胡萝卜', category: '蔬菜' },
{ id: 3, name: '橙子', category: '水果' }
],
fuse: null,
searchResults: []
}
},
mounted() {
const options = {
keys: ['name', 'category'],
threshold: 0.4
}
this.fuse = new Fuse(this.items, options)
},
watch: {
searchQuery(newVal) {
this.searchResults = newVal ?
this.fuse.search(newVal).map(result => result.item) :
this.items
}
}
}
实现防抖优化性能
对于频繁触发的搜索输入,可以使用防抖函数来优化性能,减少不必要的计算。
methods: {
debounceSearch: _.debounce(function(query) {
this.performSearch(query)
}, 300),
performSearch(query) {
// 搜索逻辑
}
},
watch: {
searchQuery(newVal) {
this.debounceSearch(newVal)
}
}
结合路由实现URL可分享的搜索
如果需要保存搜索状态,可以结合Vue Router实现URL中包含搜索参数的功能。
watch: {
searchQuery(newVal) {
this.$router.push({
query: {
q: newVal
}
})
this.performSearch(newVal)
}
},
created() {
if (this.$route.query.q) {
this.searchQuery = this.$route.query.q
this.performSearch(this.$route.query.q)
}
}






