vue3.2-setup语法糖中同时使用具名插槽和作用域插槽

602 阅读1分钟

题引:

在vue3的使用中,我们经常会使用UI组件库进行开发,那就不难免对已经封装好的UI组件库进行特殊处理。如我遇到的问题就是:element-plus 中的 el-talbe 进行特殊的列展示,那就需要同时使用 具名插槽和作用域插槽 ,但是居然发现两者无法共存,于是有了这篇文章。

正文:

由于项目中 el-table 使用过多,于是进行了封装,通过传递配置的方式进行多维度使用。 这是我进行简单的封装组件

// BaseTable.vue
<template>
  <el-table
    :data="data"
    style="width: 100%"
    border
    stripe
    highlight-current-row
  >
    <template v-for="(item, index) in dataConfig" :key="item.label">
        <el-table-column
          :label="item.label"
          :prop="item.prop"
          :align="item.align"
          :width="item.width"
          :sortable="item.sortable"
          :type="item.type"
        >
         // 重点在这里
         // 用:name绑定插槽名
         // 用v-bind="{item,index}"绑定传递的数据
          <template v-if="item.slot">
            <slot :name="item.slotName" v-bind="{ item, index }"></slot>
          </template>
        </el-table-column>
    </template>
  </el-table>
</template>

我们可以发现,在 slot 的使用中,我是通过 v-bind 来绑定插槽的传值,这样做是很直观的看出我们向上组件传递的参数。

那么回归正。我们在接受的时候,就可以通过以下的方式来接受slot传递的值,以及同时使用具名插槽

<BaseTable v-bind="dataConfig.config1" :data="innerLefTableData">
    // 重点在这:
    // 以往使用具名插槽定位时是用: v-slot:slotName / #slotName
    // 以往使用作用域插槽是用: v-slot="slotProps"
    // 在以往的认知中可能会这样来同时使用两种插槽,但是这会提示错误且无法生效的。
    <template v-slot:check v-slot="{item,index}">
        <span>{{ item.label }}</span>
    </template>
    
    // 但是这样混合使用是正确的:v-slot:slotName="slotProps" 或者解构 v-slot:slotName="{item,index}"
    <template v-slot:check="{item,index}">
        <span>{{ item.label }}</span>
    </template>
</BaseTable>

通过上面的方式,我们就可以同时使用两种插槽来满足我们的开发模式了。

结尾:

以上就是如何在setup中同时使用具名插槽和作用域插槽的方法。我们下期再见。