vue实现数据搜索
实现 Vue 数据搜索的方法
在 Vue 中实现数据搜索通常涉及对本地数据或 API 返回的数据进行过滤和展示。以下是几种常见的实现方式:
使用计算属性过滤数据
计算属性是 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:
<script>
export default {
data() {
return {
searchQuery: '',
items: [],
allItems: []
}
},
created() {
this.fetchItems()
},
watch: {
searchQuery(newVal) {
this.searchItems(newVal)
}
},
methods: {
async fetchItems() {
const response = await api.getItems()
this.allItems = response.data
this.items = this.allItems
},
searchItems(query) {
if (!query) {
this.items = this.allItems
return
}
this.items = this.allItems.filter(item =>
item.name.toLowerCase().includes(query.toLowerCase())
)
}
}
}
</script>
使用 Vuex 管理搜索状态
在大型应用中,可以使用 Vuex 集中管理搜索状态:
// store.js
export default new Vuex.Store({
state: {
searchQuery: '',
allItems: [],
filteredItems: []
},
mutations: {
SET_SEARCH_QUERY(state, query) {
state.searchQuery = query
},
SET_ITEMS(state, items) {
state.allItems = items
state.filteredItems = items
},
FILTER_ITEMS(state) {
state.filteredItems = state.allItems.filter(item =>
item.name.toLowerCase().includes(state.searchQuery.toLowerCase())
)
}
},
actions: {
async fetchItems({ commit }) {
const response = await api.getItems()
commit('SET_ITEMS', response.data)
},
updateSearchQuery({ commit }, query) {
commit('SET_SEARCH_QUERY', query)
commit('FILTER_ITEMS')
}
}
})
使用第三方库实现高级搜索
对于更复杂的搜索需求,可以考虑使用 Fuse.js 等模糊搜索库:
import Fuse from 'fuse.js'
// 在组件中
methods: {
setupFuse() {
const options = {
keys: ['name', 'description'],
threshold: 0.4
}
this.fuse = new Fuse(this.allItems, options)
},
searchItems(query) {
if (!query) {
this.items = this.allItems
return
}
this.items = this.fuse.search(query).map(result => result.item)
}
}
实现防抖优化性能
对于频繁触发的搜索输入,可以添加防抖功能:
import debounce from 'lodash.debounce'
// 在组件中
created() {
this.debouncedSearch = debounce(this.searchItems, 300)
},
watch: {
searchQuery(newVal) {
this.debouncedSearch(newVal)
}
}
以上方法可以根据具体需求选择或组合使用,实现 Vue 应用中的数据搜索功能。







