elementui中el-tabs组件下的组件包含el-table,解决切换tab时table闪动问题

7 篇文章 0 订阅
2 篇文章 0 订阅

起初为解决上述问题,使用了笨法,就是利用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();
                    }
                }
            })
        }
    }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值