vue实现搜索效果
Vue 实现搜索功能的方法
基础搜索实现
在 Vue 中实现搜索功能,可以通过 v-model 绑定输入框,结合计算属性过滤数据:
<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>
使用 Lodash 防抖
对于频繁触发的搜索,可以使用 Lodash 的防抖功能优化性能:
import { debounce } from 'lodash'
export default {
data() {
return {
searchQuery: '',
items: [],
allItems: []
}
},
created() {
this.debouncedSearch = debounce(this.doSearch, 300)
},
watch: {
searchQuery(newVal) {
this.debouncedSearch(newVal)
}
},
methods: {
doSearch(query) {
this.items = this.allItems.filter(item =>
item.name.toLowerCase().includes(query.toLowerCase())
)
}
}
}
服务端搜索
对于大数据量搜索,建议使用服务端接口:
methods: {
async searchItems() {
try {
const response = await axios.get('/api/items', {
params: { q: this.searchQuery }
})
this.items = response.data
} catch (error) {
console.error('搜索出错:', error)
}
}
}
高级搜索组件
可以封装可复用的搜索组件:
<!-- SearchComponent.vue -->
<template>
<div class="search-box">
<input
v-model="internalValue"
@input="handleInput"
placeholder="搜索..."
/>
<button @click="$emit('search', internalValue)">搜索</button>
</div>
</template>
<script>
export default {
props: ['value'],
data() {
return {
internalValue: this.value
}
},
watch: {
value(newVal) {
this.internalValue = newVal
}
},
methods: {
handleInput() {
this.$emit('input', this.internalValue)
}
}
}
</script>
使用 Vuex 管理搜索状态
在大型应用中,可以使用 Vuex 集中管理搜索状态:
// store.js
export default new Vuex.Store({
state: {
searchQuery: '',
searchResults: []
},
mutations: {
SET_SEARCH_QUERY(state, query) {
state.searchQuery = query
},
SET_SEARCH_RESULTS(state, results) {
state.searchResults = results
}
},
actions: {
async search({ commit }, query) {
commit('SET_SEARCH_QUERY', query)
const results = await api.search(query)
commit('SET_SEARCH_RESULTS', results)
}
}
})
这些方法涵盖了从基础到高级的 Vue 搜索实现方式,可以根据项目需求选择合适的方案。







