vue实现条件查询
Vue 实现条件查询的方法
在 Vue 中实现条件查询通常需要结合表单输入、数据绑定和过滤逻辑。以下是几种常见的实现方式:

使用计算属性过滤数据
<template>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</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 监听查询条件变化
<script>
export default {
data() {
return {
searchQuery: '',
items: [],
filteredItems: []
}
},
watch: {
searchQuery(newVal) {
this.filterItems(newVal)
}
},
methods: {
filterItems(query) {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(query.toLowerCase())
)
}
}
}
</script>
结合多个查询条件
<template>
<input v-model="filters.name" placeholder="名称">
<input v-model="filters.price" type="number" placeholder="价格">
<ul>
<li v-for="product in filteredProducts" :key="product.id">
{{ product.name }} - {{ product.price }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
filters: {
name: '',
price: null
},
products: [
{ id: 1, name: '手机', price: 1999 },
{ id: 2, name: '电脑', price: 5999 }
]
}
},
computed: {
filteredProducts() {
return this.products.filter(product => {
const nameMatch = product.name.toLowerCase().includes(
this.filters.name.toLowerCase()
)
const priceMatch = this.filters.price
? product.price <= this.filters.price
: true
return nameMatch && priceMatch
})
}
}
}
</script>
使用第三方库实现高级搜索
对于更复杂的搜索需求,可以考虑使用 Fuse.js 等模糊搜索库:
import Fuse from 'fuse.js'
export default {
data() {
return {
search: '',
list: [...],
fuseOptions: {
keys: ['name', 'description'],
threshold: 0.4
}
}
},
computed: {
searchResults() {
if (!this.search) return this.list
const fuse = new Fuse(this.list, this.fuseOptions)
return fuse.search(this.search).map(result => result.item)
}
}
}
服务器端条件查询
当数据量较大时,应该考虑将查询条件发送到后端:
methods: {
async searchItems() {
const params = {
keyword: this.searchQuery,
page: this.currentPage
}
const response = await axios.get('/api/items', { params })
this.items = response.data
}
}
以上方法可以根据具体需求选择使用,计算属性方式适合前端过滤少量数据,而服务器端查询适合大数据量场景。







