vue-插槽 slot

插槽,也就是slot,是组件的一块HTML模板,这块模板显示不显示、以及怎样显示由父组件来决定。 实际上,一个slot最核心的两个概念这里就点出来了,是显不显示和怎样显示

“占坑”,在组件模板中占好了位置,当使用该组件标签时候,组件标签里面的内容就会自动填坑(替换组件模板中<slot>位置),当插槽也就是坑<slot name= ” mySlot ” >有命名时,组件标签中使用属性slot= ” mySlot ” 的元素就会替换该对应位置内容

在 2.6.0 中,具名插槽和作用域插槽的语法 slotslot-scope 被弃用,使用新的语法 v-slot 代替

匿名插槽

组件中有单个或多个未命名slot标签时

<template>    
<div>
    <slot></slot>
    <slot  style=”color:blue;” >这是在slot上添加了样式</slot>
    <slot  name=”mySlot”>这是拥有命名的slot的默认内容</slot>
</div>
</template>

具名插槽

组件中有多个命名的slot 插槽时,可以实现父组件对子组件的指定位置显示内容或传参

<!-- old -->
<children>
  <template slot="header">
    <h1>Here might be a page title</h1>
  </template>
  <template slot="default">
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </template>
</children>

<!-- new -->
<children>
  <template v-slot:header>
  <!--  <template #header> 具名插槽可缩写形式 -->
    <h1>Here might be a page title</h1>
  </template>
  <template v-slot:default>
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </template>
</children>

作用域插槽

作用域插槽实际上是带有数据的插槽,可以获取到父组件传递的参数,将这些参数使用到子组件插槽里,如表格中某一列的插槽

<!-- old -->
<children>
  <template slot="default" slot-scope="scope">
    {{ scope.user.firstName }}
  </template>
</children>

<!-- new -->
<children>
  <template v-slot:default="scope">
  // default可以省略,默认插槽的缩写语法 <template v-slot="scope">
    {{ scope.user.firstName }}
  </template>
</children>

scope相当于一行的数据, scope.row相当于当前行的数据对象。这里就是用插槽 拿到当前行 row是个内置的属性 ,{{scope.$index}}可以获取当前行的index。

常用场景:

  • 需要在列表中进行非文本渲染,比如渲染图片、按钮、进度条等;

  • 需要对渲染的数据再进行操作时,比如对得到的数据进行再分割

 

posted @ 2023-08-25 16:54  huiyii  阅读(8)  评论(0编辑  收藏  举报