多表格场景
当同一页面存在多个 PageTemplate 组件时(如 Tab 切换场景),默认的表格高度计算会互相干扰。通过传入 instanceKey 可以为每个实例创建独立的高度状态。
使用场景
- 同一页面多个表格
- Tab 切换保留状态
- 使用
v-show或 CSS 控制显示/隐藏的多表格场景
基础用法
vue
<script setup>
import { PageTemplate, Table, useState, useTableHeight } from 'vue-admin-kit'
// 为每个 Tab 创建唯一的实例标识符
const INSTANCE_KEYS = {
table1: Symbol('table1'),
table2: Symbol('table2')
} as const
const active = ref('1')
// 提供给子组件,用于在切换时触发高度计算
provide('activeTab', active)
</script>
<template>
<div>
<el-tabs v-model="active">
<el-tab-pane label="表格1" name="1" />
<el-tab-pane label="表格2" name="2" />
</el-tabs>
<div class="tab-panels">
<div class="tab-panel" :class="{ 'is-active': active === '1' }">
<Table1 :instance-key="INSTANCE_KEYS.table1" tab-key="1" />
</div>
<div class="tab-panel" :class="{ 'is-active': active === '2' }">
<Table2 :instance-key="INSTANCE_KEYS.table2" tab-key="2" />
</div>
</div>
</div>
</template>
<style scoped>
.tab-panels {
position: relative;
}
.tab-panel {
visibility: hidden;
opacity: 0;
position: absolute;
top: 0;
left: 0;
width: 100%;
pointer-events: none;
}
.tab-panel.is-active {
visibility: visible;
opacity: 1;
position: relative;
pointer-events: auto;
}
</style>子组件实现
vue
<!-- Table1.vue / Table2.vue -->
<script setup>
import { PageTemplate, Table, useState, useTableHeight } from "vue-admin-kit";
const props = defineProps({
instanceKey: { type: Symbol, default: undefined },
tabKey: { type: String, default: "" },
});
const activeTab = inject("activeTab");
const { calculateTableHeight } = useTableHeight({
instanceKey: props.instanceKey,
});
// 监听 tab 切换,当切换到当前 tab 时重新计算高度
watch(
() => activeTab?.value,
(newVal) => {
if (newVal === props.tabKey) {
setTimeout(() => calculateTableHeight(), 50);
}
}
);
useState({
api: {
/* ... */
},
searchConfig: [
/* ... */
],
formConfig: [
/* ... */
],
columnsConfig: [
/* ... */
],
});
</script>
<template>
<PageTemplate :instance-key="instanceKey">
<template #table>
<Table />
</template>
</PageTemplate>
</template>工作原理
- 默认单例模式:不传
instanceKey时,所有组件共享同一个高度状态 - 实例隔离模式:传入
instanceKey后,相同 key 的组件共享状态,不同 key 互不干扰 - 自动优化:隔离实例在高度未变化时会跳过重复计算