实战教程3:不用后端调用 - Vue中el-table如何实现前端纯静态搜索与清空功能?详解el-table表格的筛选与查询重置操作
本文已参与「新人创作礼」活动,一起开启掘金创作之路。
一、功能效果描述
由于数据量较大,每时每分都会产生数据,当前列表只展示进入页面的最新数据。其中的查询和重置功能都是基于当前数据的,所以要求不调接口,只是前端的查询并展示。但是点击刷新按钮,会调接口,请求到最近的数据,此时列表刷新为最近数据。
至于调接口情况可以看动图中右侧效果。
(1)利用el-table的筛选功能进行前端内容的筛选
(2)点击查询按钮,使用数组操作实现查询,并显示查询结果;对于查询之后再次查询能够还原原始查询数组。
(3)重置功能、刷新功能==>调接口显示最新数据
二、el-table自带筛选功能
使用到el-table的筛选功能:Element - The world's most popular Vue UI framework
在列中设置filtersfilter-method属性即可开启该列的筛选,filters 是一个数组,filter-method是一个方法,它用于决定某些数据是否显示,会传入三个参数:value, row 和 column。
因此,我们要在需要筛选的列上加上两项:
:filters="筛选备选项数组"
:filter-method="filterHandler"
prop="stationName"
label="站点名称"
align="center"
:filters="stationList"
:filter-method="filterHandler"
>
</el-table-column>
filterHandler(value, row, column) {
const property = column["property"];
return row[property] === value;
},
三、前端假查询重置功能
1. el-form表单
<el-form-item label="设备名称:">
<el-input
v-model="formInline1.name"
placeholder="请输入"
style="height: 32px"
></el-input>
</el-form-item>
<el-form-item>
<el-button-group>
<el-button @click="reset1">重置</el-button>
<el-button type="primary" @click="search1">查询</el-button>
</el-button-group>
</el-form-item>
</el-form>
<div class="title">
<div class="title-name">报表详情:</div>
<div class="title-refresh" @click="getPerimeterData1">
<i class="el-icon-refresh" style="margin-right: 8px"></i>刷新</div>
</div>
2.el-table表格数据
:data="tableData1"
style="width: 98%"
class="tableBox"
stripe
max-height="450"
>
<el-table-column label="序号" prop="index" width="55">
<template slot-scope="scope">
<span>{{ scope.$index + 1 }}</span>
</template>
</el-table-column>
<el-table-column prop="sysName" label="设备名称" align="center">
</el-table-column>
<el-table-column label="操作" align="center" width="100">
<template slot-scope="scope">
<el-button
type="text"
:style="'padding:none'"
@click="handleDetail1(scope.row)"
>查看</el-button
>
</template>
</el-table-column>
</el-table>
表格绑定了tableData1,是根据getPerimeterData1()函数调接口获取到的列表数据
3. search功能
思路:遍历tableData1数组,对于满足条件的数组元素push到searchData数组,并最终把searchData赋值给tableData1.
search1() {
const key = this.formInline1.name; // 查询表单中的输入
const vm = this;
this.tableData1.forEach(function (item) {
if (item.sysName.indexOf(key) > -1) {
vm.searchData1.push(item);
}
});
this.tableData1 = this.searchData1;
},
问题1:查询一次后,再次查询,tableData变成了两次查询的并集===>在每次查询前清空searchdata
问题2:先查询一个不存在的数据后, 再查询其他有数据的也不会显示了。===>因为查询一次之后,tableData的原始查询数组变小了===>需要有一份备份的tableData数据,即tableDataTemp,每次操作时使用tableDatatemp来进行
修改后的无误代码:
search1() {
this.flag1 = true;
const key = this.formInline1.name; // 查询表单中的输入
const vm = this;
this.searchData1 = []; //清空查询数组-防止多次查询记录一直被push在最后
console.log("查询前", this.tableDataTemp1);
this.tableDataTemp1.forEach(function (item) {
if (item.sysName.indexOf(key) > -1) {
vm.searchData1.push(item);
}
});
// this.resetData1 = this.tableData1;
this.tableData1 = this.searchData1;
console.log("查询后", this.tableData1);
},
4. reset重置功能
reset1() {
this.getPerimeterData1();
this.formInline1 = {
name: "",
};
},