vue实现多条件查询
Vue实现多条件查询的方法
数据绑定与表单设计
在Vue中通过v-model绑定表单输入框,收集用户输入的查询条件。例如查询姓名和年龄:
<template>
<div>
<input v-model="queryParams.name" placeholder="姓名">
<input v-model="queryParams.age" placeholder="年龄" type="number">
<button @click="handleSearch">查询</button>
</div>
</template>
<script>
export default {
data() {
return {
queryParams: {
name: '',
age: null
},
originalData: [],
filteredData: []
}
}
}
</script>
处理查询逻辑
在methods中实现过滤逻辑,使用数组的filter方法进行多条件匹配:
methods: {
handleSearch() {
this.filteredData = this.originalData.filter(item => {
const nameMatch = !this.queryParams.name ||
item.name.includes(this.queryParams.name)
const ageMatch = !this.queryParams.age ||
item.age === Number(this.queryParams.age)
return nameMatch && ageMatch
})
}
}
动态渲染结果
使用计算属性实现实时过滤,避免手动触发查询:
computed: {
filteredData() {
return this.originalData.filter(item => {
const nameMatch = !this.queryParams.name ||
item.name.toLowerCase().includes(this.queryParams.name.toLowerCase())
const ageMatch = this.queryParams.age === null ||
item.age === Number(this.queryParams.age)
return nameMatch && ageMatch
})
}
}
复杂条件处理
对于更复杂的查询条件,可以采用对象遍历方式:
methods: {
advancedFilter() {
return this.originalData.filter(item => {
return Object.keys(this.queryParams).every(key => {
if (!this.queryParams[key]) return true
return String(item[key]).includes(String(this.queryParams[key]))
})
})
}
}
使用第三方库
对于大型数据集,可以考虑使用lodash的_.filter方法:
import _ from 'lodash'
methods: {
lodashFilter() {
this.filteredData = _.filter(this.originalData, this.queryParams)
}
}
注意事项
- 数字类型比较需显式转换,避免字符串与数字的隐式转换问题
- 空值处理要完善,当查询条件为空时应返回全部数据
- 对于中文搜索,建议统一转为小写或大写进行比较
- 大数据量时考虑防抖处理,避免频繁触发过滤计算







