vue实现表格查询
Vue 实现表格查询功能
数据准备 在 Vue 组件中定义表格数据和查询条件绑定的变量:
data() {
return {
tableData: [], // 表格数据
searchQuery: '', // 查询条件
originalData: [] // 原始数据备份
}
}
获取初始数据 在 mounted 钩子中获取初始数据并备份:
mounted() {
this.fetchData();
},
methods: {
fetchData() {
// 模拟API请求
this.tableData = [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 },
{ id: 3, name: '王五', age: 28 }
];
this.originalData = [...this.tableData];
}
}
实现查询方法 添加过滤方法处理查询逻辑:
methods: {
handleSearch() {
if (!this.searchQuery) {
this.tableData = [...this.originalData];
return;
}
const query = this.searchQuery.toLowerCase();
this.tableData = this.originalData.filter(item => {
return Object.values(item).some(
value => String(value).toLowerCase().includes(query)
);
});
}
}
模板部分 在模板中添加搜索输入框和表格展示:
<template>
<div>
<input
v-model="searchQuery"
@input="handleSearch"
placeholder="输入查询内容"
/>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</div>
</template>
高级查询实现
多条件查询 扩展查询功能支持多字段精确匹配:
data() {
return {
searchParams: {
name: '',
age: ''
}
}
},
methods: {
advancedSearch() {
this.tableData = this.originalData.filter(item => {
return (
(this.searchParams.name === '' ||
item.name.includes(this.searchParams.name)) &&
(this.searchParams.age === '' ||
item.age == this.searchParams.age)
);
});
}
}
分页支持 添加分页功能:
data() {
return {
currentPage: 1,
pageSize: 5
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
return this.tableData.slice(start, start + this.pageSize);
},
totalPages() {
return Math.ceil(this.tableData.length / this.pageSize);
}
}
性能优化
防抖处理 为搜索输入添加防抖:
import { debounce } from 'lodash';
methods: {
handleSearch: debounce(function() {
// 搜索逻辑
}, 300)
}
虚拟滚动 大数据量时使用虚拟滚动:
<template>
<RecycleScroller
class="scroller"
:items="tableData"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<tr>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</template>
</RecycleScroller>
</template>
服务端查询
API集成 与后端API集成实现服务端查询:
methods: {
async fetchServerData(params) {
try {
const res = await axios.get('/api/data', { params });
this.tableData = res.data;
} catch (error) {
console.error(error);
}
}
}






