vue列表查询实现
实现 Vue 列表查询功能
1. 数据绑定与列表渲染
使用 v-for 指令渲染列表数据,绑定到组件的 data 或 props:
<template>
<ul>
<li v-for="item in filteredList" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
rawList: [{id: 1, name: 'Apple'}, {id: 2, name: 'Banana'}],
searchQuery: ''
}
}
}
</script>
2. 计算属性实现过滤
通过计算属性动态过滤列表,避免每次输入都触发方法调用:
computed: {
filteredList() {
return this.rawList.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
3. 添加搜索输入框
在模板中添加搜索输入框,使用 v-model 双向绑定搜索关键词:
<input
type="text"
v-model="searchQuery"
placeholder="Search..."
class="search-input"
>
4. 优化搜索性能
对于大数据量列表,可添加防抖处理:
import _ from 'lodash';
export default {
methods: {
search: _.debounce(function() {
// 执行搜索逻辑
}, 300)
}
}
5. 服务端搜索实现
当数据量较大时,可改为服务端搜索:
methods: {
async fetchSearchResults() {
const res = await axios.get('/api/items', {
params: { q: this.searchQuery }
});
this.filteredList = res.data;
}
},
watch: {
searchQuery(newVal) {
if(newVal.length > 2) this.fetchSearchResults();
}
}
6. 高级过滤功能
实现多条件复合搜索:
computed: {
filteredList() {
return this.rawList.filter(item => {
const matchesName = item.name.toLowerCase().includes(this.searchQuery.toLowerCase());
const matchesCategory = this.selectedCategory ?
item.category === this.selectedCategory : true;
return matchesName && matchesCategory;
});
}
}
7. 空状态提示
添加搜索结果为空时的提示:
<template>
<div v-if="filteredList.length === 0" class="empty-state">
No items found
</div>
</template>






