起初为解决上述问题,使用了笨法,就是利用tabs组件的tab-click事件,在事件中调用table的doLayout方法,但是这么写比较繁琐,需要改动好几个地方,遂想优化一下,于是上网上查些资料,有人说直接table中追加key或者table-column中追加key,也有人说在pane中用if条件,但都达不到预期效果。
偶然间想到一个办法,基本逻辑是通过自定义指令的方式调用表格的doLayout方法。给el-tabs组件添加layout指令,用update指令钩子在VNode更新后查找当前激活的tab组件实例,并在当前激活tab下查找el-table组件实例,通过找到的table组件实例调用doLayout方法实现。详细见以下代码:
// 向下找到最近的指定组件
function findComponentDownward(context, componentName) {
const childrens = context.$children;
let children = null;
if (childrens.length) {
for (const child of childrens) {
const name = child.$options._componentTag;
if (name === componentName) {
children = child;
break;
} else {
children = findComponentDownward(child, componentName);
if (children) break;
}
}
}
return children;
}
// 向下找到所有指定的组件
function findComponentsDownward(context, componentName) {
return context.$children.reduce((components, child) => {
if (child.$options._componentTag === componentName) components.push(child);
const foundChilds = findComponentsDownward(child, componentName);
return components.concat(foundChilds);
}, []);
}
// 自定义指令
export default {
// el-tabs组件下有el-table组件时切换tab表格闪动及样式错乱问题解决
layout: {
update(el, binding, vNode) {
let that = vNode.context;
that.$nextTick(() => {
// 找到激活的pane组件
let panes = findComponentsDownward(that, 'el-tab-pane') || [];
let pane = panes.find(item => item.active);
// 查找激活pane下的table
if (!!pane) {
let table = findComponentDownward(pane, 'el-table');
if (!!table) {
table.doLayout();
}
}
})
}
}
}