需求:树形表格,实现关键字搜索,并滚动到指定位置
解决方案:
因为u-table渲染出来是将所有一级,二级,三级。。。都渲染到了tr中,但是tr并没有分一级,二级,三级。后台返回的数据结构是树形,就是含children字段的数组对象结构,首先得先把这个数据做一个扁平化处理,将所有子子孙孙都提为第一级,去掉所有children,得到的新的数组就能和页面渲染出来的元素位置索引能够一一对应。
我的table每一个tr的高度是60,我们只需要将输入关键字在扁平化处理后的数组中进行filter,并记录索引index位置,索引乘以60就是需要滚动的高度。
以下字段需要在data中定义
plTableSearch: '', //市场统填费关键字
aimIndex: 0, //目标索引
nowIndex: 0, //记录当前展示的索引位置
matchList: [], //匹配关键词后的数组
flatteningTreeList: [], //将后台返回的数据去掉child
核心代码
从后台获取到树形结构的数据后,调用此方法,将树形转化为平常的数组对象,存储到 flatteningTreeList 中
/** 数组扁平化*/
treetolist(tree) {
if (tree && tree.length > 0) {
tree.forEach((sub) => {
this.flatteningTreeList.push(sub);
if (sub.children && sub.children.length > 0) {
this.treetolist(sub.children, this.flatteningTreeList);
}
});
}
},
在u-table外加入一个input输入框,用于输入关键字,plTableSearchChange方法用于监听input框变化,进行filter过滤;插槽中的next方法用于查找下一个匹配对象
<el-input v-model="plTableSearch" @input="plTableSearchChange" :clearable="true" size="mini" placeholder="报价名称搜索">
<template slot="append"><span v-if="matchList.length >0 &&plTableSearch.length >0" class="next-mate"
@click="next">下一个</span></template></el-input>
plTreeTable为u-table的ref
输入关键字后,方法会将所有匹配的对象,塞入一个数组中,并记录索引,默认将数组中第一个数据作为表格第一个展示的内容,即:若第一个对象中记录的index为8,那高度就为滚动 8 *60
//输入关键字,检索数据
plTableSearchChange() {
this.matchList = this.flatteningTreeList.filter((item, index) => {
if (
!this.plTableSearch ||
item.quotationName
.toLowerCase()
.includes(this.plTableSearch.toLowerCase())
) {
item.index = index
return item
}
})
if (this.matchList.length > 0) {
this.aimIndex = this.matchList[this.nowIndex].index
}
//plTreeTable为u-table的ref,后面的一堆是u-table的元素结构,照搬就行
this.$refs.plTreeTable.$refs.singleTable.$refs.bodyWrapper.scrollTop =
this.aimIndex * 60
},
这里用nowIndex作为当先显示项的索引记录
//下一个匹配项
next() {
if (this.nowIndex < this.matchList.length - 1) {
this.nowIndex++
} else {
this.nowIndex = 0
}
this.aimIndex = this.matchList[this.nowIndex].index
this.$refs.plTreeTable.$refs.singleTable.$refs.bodyWrapper.scrollTop =
this.aimIndex * 60
}