一、场景说明
- 点击按钮会打开抽屉,在抽屉内进行某些操作,关闭抽屉后会调接口刷新表格数据。
- 刷新数据后,树形表格全部展开,且滚动条定位到点击按钮时的位置。
二、代码实现
<template>
<div class="box">
<vxe-button @click="openDrawer">新增</vxe-button>
<vxe-table
:data="tableData"
max-height="400px"
class="table"
ref="xTable"
:tree-config="{ children: 'children', expandAll: true }"
>
<vxe-column field="name" title="Name" tree-node></vxe-column>
<vxe-column field="sex" title="Sex"></vxe-column>
<vxe-column field="age" title="Age"></vxe-column>
</vxe-table>
<a-drawer title="抽屉" :visible="visible" @close="onClose">
<p>假设进行了一些操作,关闭抽屉后会刷新表格数据。</p>
<p>刷新表格数据后,需要将滚动条定位到打开抽屉前的位置。</p>
</a-drawer>
</div>
</template>
<script>
export default {
data() {
return {
visible: false,
tableData: [
{
name:'一班',
children: [
{ id: 10001, name: 'Test1', role: 'Develop', sex: 'Man', age: 28, address: 'test abc' },
{ id: 10002, name: 'Test2', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
{ id: 10003, name: 'Test3', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
{ id: 10004, name: 'Test4', role: 'Designer', sex: 'Women', age: 24, address: 'Shanghai' },
{ id: 10005, name: 'Test5', role: 'Develop', sex: 'Man', age: 28, address: 'test abc' },
{ id: 10006, name: 'Test6', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
{ id: 10007, name: 'Test7', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
{ id: 10008, name: 'Test8', role: 'Designer', sex: 'Women', age: 24, address: 'Shanghai' }
]
},
{
name:'二班',
children: [
{ id: 10009, name: 'Test9', role: 'Develop', sex: 'Man', age: 28, address: 'test abc' },
{ id: 10010, name: 'Test10', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
{ id: 10011, name: 'Test11', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
{ id: 10012, name: 'Test12', role: 'Designer', sex: 'Women', age: 24, address: 'Shanghai' },
{ id: 10013, name: 'Test13', role: 'Develop', sex: 'Man', age: 28, address: 'test abc' },
{ id: 10014, name: 'Test14', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
{ id: 10015, name: 'Test15', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
{ id: 10016, name: 'Test16', role: 'Designer', sex: 'Women', age: 24, address: 'Shanghai' }
]
},
],
scrollHeight: 0
}
},
methods: {
onClose() {
this.visible = false
setTimeout(() => {
this.$refs.xTable.setAllTreeExpand(true)
this.$nextTick(() => {
this.$refs.xTable.scrollTo(0, this.scrollHeight)
})
}, 500)
},
openDrawer() {
let { scrollTop } = this.$refs.xTable.getScroll()
this.scrollHeight = scrollTop
this.visible = true
}
}
}
</script>
<style>
.box {
margin: 100px;
}
.table {
margin: 5px 0;
}
</style>
三、关键代码
- 记录滚动条位置
let { scrollTop } = this.$refs.xTable.getScroll()
this.scrollHeight = scrollTop
- 还原滚动条位置(可能需要配合延时器)
this.$refs.xTable.scrollTo(0, this.scrollHeight)
- 展开树形表格(可能需要配合延时器)
this.$refs.xTable.setAllTreeExpand(true)