vue 动态插槽 v-slot #

61 阅读1分钟

vue 动态插槽

今天遇到一个需求要动态插槽减少template中的代码量,查了好多资料,发现讲的都不够细致, 把我最后实现效果展现出来:

    <el-table
      :columns="columns"
      :data="list"
  <template
     v-for="item in templateSlot"
     v-slot:[item]="scope"
   >
     <div :key="item">
       {{ scope.scope.row[item] }}
     </div>
   </template>
 </el-table>
 
   data() {
     return {
       // template slot列表
       templateSlot: [
         'peom1',
         'author',
       ],
     }
   }

可以看到主要点在

v-slot:[item]="scope"

如果是写死的情况

v-slot:pemo1="scope"

使用括号 可以动态绑定,且scope可以绑定当前行的数据,用于下面使用。

这部分是vue2.6新增的语法,之前写法是

slot="pemo1"
slot-scope="scope"

其实vue2.6还提供了另一种方式,即通过# 来实现slot的绑定,写法如下

<template #pemo1 >
  {{  }}
</template>
<template #pemo1="{ scope }" >
 {{ scope.pemo1 }}
</template>

举一反三吧,最上面的写法就如下了:

    <el-table
      :columns="columns"
      :data="list"
  <template
     v-for="item in templateSlot"
     #[item]="scope"
   >
     <div :key="item">
       {{ scope.scope.row[item] }}
     </div>
   </template>
 </el-table>
 
   data() {
     return {
       // template slot列表
       templateSlot: [
         'peom1',
         'author',
       ],
     }
   }

其他插槽用法还有很多,插槽真的博大精深 还需研究。