vue实现搜索列表
实现搜索列表功能
数据绑定与搜索逻辑
在Vue中实现搜索列表功能需要绑定输入框和列表数据,通过计算属性或方法过滤列表。
<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredList" :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: {
filteredList() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用第三方库增强搜索
对于更复杂的搜索需求,可以使用Fuse.js等模糊搜索库。

import Fuse from 'fuse.js'
export default {
methods: {
fuzzySearch() {
const options = {
keys: ['name'],
threshold: 0.4
}
const fuse = new Fuse(this.items, options)
return fuse.search(this.searchQuery)
}
}
}
异步搜索实现
当数据需要从API获取时,可以使用异步搜索模式。

export default {
methods: {
async fetchResults() {
const response = await axios.get('/api/items', {
params: { q: this.searchQuery }
})
this.items = response.data
}
},
watch: {
searchQuery(newVal) {
if (newVal.length > 2) {
this.fetchResults()
}
}
}
}
性能优化
对于大型数据集,考虑添加防抖功能避免频繁触发搜索。
import { debounce } from 'lodash'
export default {
created() {
this.debouncedSearch = debounce(this.fetchResults, 500)
},
watch: {
searchQuery() {
this.debouncedSearch()
}
}
}
样式增强
为搜索结果添加高亮显示功能。
<li v-for="item in filteredList" v-html="highlight(item.name)"></li>
<script>
methods: {
highlight(text) {
if (!this.searchQuery) return text
const regex = new RegExp(this.searchQuery, 'gi')
return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>






