vue实现精准查询
实现精准查询的方法
在Vue中实现精准查询通常涉及以下几个关键步骤:
数据绑定与输入处理
使用v-model双向绑定查询关键词,监听输入变化触发查询:
<template>
<input v-model="searchKeyword" @input="handleSearch" placeholder="输入查询关键词"/>
</template>
<script>
export default {
data() {
return {
searchKeyword: '',
originalData: [...], // 原始数据
filteredData: [] // 过滤后数据
}
}
}
</script>
精确匹配算法 采用全等匹配或正则表达式实现精准匹配:
methods: {
handleSearch() {
if (!this.searchKeyword.trim()) {
this.filteredData = [...this.originalData]
return
}
// 精确匹配方案1:全等匹配
this.filteredData = this.originalData.filter(item =>
item.name === this.searchKeyword.trim()
)
// 精确匹配方案2:正则精确匹配
const reg = new RegExp(`^${this.searchKeyword.trim()}$`, 'i')
this.filteredData = this.originalData.filter(item =>
reg.test(item.name)
)
}
}
性能优化 对于大数据量场景采用防抖处理:
import _ from 'lodash'
export default {
created() {
this.debouncedSearch = _.debounce(this.handleSearch, 300)
},
methods: {
handleSearch() {
// 查询逻辑
}
}
}
多字段精确查询 扩展为支持多字段的精确查询:
handleSearch() {
const keyword = this.searchKeyword.trim().toLowerCase()
this.filteredData = this.originalData.filter(item =>
['name', 'id', 'category'].some(field =>
String(item[field]).toLowerCase() === keyword
)
)
}
后端精准查询 与后端API配合实现服务端精确查询:
async handleSearch() {
try {
const response = await axios.get('/api/search', {
params: {
keyword: this.searchKeyword,
exactMatch: true
}
})
this.filteredData = response.data
} catch (error) {
console.error(error)
}
}
注意事项
- 精确查询区分大小写时需统一转换大小写进行比较
- 空值处理需重置为显示全部数据
- 数字类型需转换为字符串后再比较
- 中文查询需注意编码一致性
扩展实现
可结合Vuex管理查询状态:

// store/modules/search.js
const actions = {
exactSearch({ commit }, keyword) {
commit('SET_FILTERED_DATA',
state.originalData.filter(item =>
item.name.toLowerCase() === keyword.toLowerCase()
)
)
}
}
通过组合这些方法,可以构建出满足不同场景需求的精准查询功能。






