vue3 封装el-table时,构造$children(类式写法)

由于业务需求(组件封装),需要在获取el-table下面的el-table-column实例

在 vue2.x 当中直接使用this.$children就可以获取到该实例

但是 vue3.x 弃用了$children,官方建议使用$ref获取子组件实例,由于el-table-column是通过插槽形式插入,且当el-table-column数过多时,不可能专门为每一个el-table-column都添加ref,在网上搜索之后发现有人建议使用$slot获取插入的组件实例,但是获取到的实例信息不足,因此决定构造一个“$children”出来

1. 使用$slots

打印$slots

console.log(this.$slots);
// 若是setup需要在setup当中接收slots参数

image

调用$slots里面的default

(this.$slots as any).default()
// 若是setup需要在setup当中接收slots参数

image

2. 构造$children

思路:思路很简单,直接在el-table-column挂载时,调用父组件的方法,并传入自身实例即可

  1. 为方便在el-table-column挂载时做处理,封装一下el-table-column
<el-table-column
    v-bind="$props"
    ref="elColumn"
    :sortable="sortable"
    :merge="merge"
    :merge-by="mergeBy"
    :formatter="compatibleFormatter"
    v-on="$attrs"
  >
    <template v-if="$slots.default" #default="scope">
      <slot v-bind="scope" />
    </template>
    <template v-if="$slots.header" #header="scope">
      <slot name="header" v-bind="scope" />
    </template>
</el-table-column>

在挂载的时候调用父方法

mounted() {
    
    
    // 获取表格列的配置
    this.columnConfig = (this.$refs as any).elColumn?.$?.columnConfig?.value

    // this.$parent获取到的是el-table组件的实例,this.$parent.$parent才是我们自己写的组件的实例
    if (this.$parent && this.$parent.$parent) {
    
    
      const _this = this;
      (this.$parent.$parent as any).setChildrenInstance(_this)
    }
}
  1. 在父组件接收实例并存放起来
    新建父组件(简写)
<el-table>
    <slot />
</el-table>

接收子组件实例

public childrens: any[] = []

public setChildrenInstance(children: any) {
    
    
    this.childrens.push(children)
}

// 在用的地方调用childrens即可 打印 console.log(this.childrens);

image

猜你喜欢

转载自blog.csdn.net/qq_43519131/article/details/127086761
今日推荐