VUE - slot的基本使用

212 阅读2分钟

权威详细内容查看VUE文档

slot是什么,简单理解为父组件希望向子组件内分发一些内容,<slot> 元素作为子组件中承载分发内容的出口。

1. 基本使用方法

父组件

<template>
<div class="button-wrapper">
      <child @click="remove">删除标签</child>
</div>
</template>

子组件

<template>
  <button>
      <slot>子组件内容</slot> <!--或者使用<slot />-->
      </button>
</template>

结果为一个内容为删除标签的button,即父组件在子组件标签中的内容替换了<slot></slot>

若子组件中没有slot,则父组件在子组件标签中的内容不会出现,而会显示 子组件内容。

2. 具名slot

子组件中可能有多个slot,要使指定内容分发到指定的slot,可以使用具名slot。而一个不带 name 的 <slot> 出口会带有隐含的名字“default”。

在子组件添加name属性

<template>
  <button>
      <slot name='slot1'>子组件内容</slot> 
  </button>
  <button>
      <slot name='slot2'>子组件内容</slot>
  </button>
</template>

父组件在一个 <template> 元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称,向指定插槽提供内容

<template>
<div>
      <child>
          <template v-slot:slot2>删除标签</template>
      </child>
</div>
</template>

则第一个按钮内显示子组件内容,第二个按钮显示删除标签。

3. 编译作用域

规则:

父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。

用文档中的例子

<navigation-link url="/profile">
  Clicking here will send you to: {{ url }}
</navigation-link>

这里的 url 会是 undefined,因为其 (指该插槽的) 内容是传递给 <navigation-link> 的而不是在 组件内部定义的。 www.jianshu.com/p/ec17c5161…

4、作用域插槽

作用域插槽可使得子组件内数据可以被父组件拿到。

子组件:

<template>
  <button>
      <slot v-bind:user='user'>{{user.lastname}}</slot>
      </button>
</template>

将 user 作为 元素的一个属性绑定上去,该属性被称为插槽prop.

父组件

<template>
<div>
      <child v-slot:default="slotProps">
      {{slotProps.user.firstname}}
      </child>
</div>
</template>

在父组件中,使用带值的的v-slot来定义包含所有插槽props的对象的名字

当被提供的内容只有默认插槽时,组件的标签才可以被当作插槽的模板来使用。这样我们就可以把 v-slot 直接用在组件上。 只有默认插槽时,可直接简写为 v-slot="slotProps"

若存在具名插槽,需要为所有的插槽使用<template>,默认插槽带有隐含的名字“default”。

<template>
<div>
      <child>
      <template  v-slot:default="slotProps">{{slotProps.user.firstname}}</template>
      <template v-slot:slot2="slot2Props">{{slot2Props.user.firstname}}</template>
      </child>
</div>
</template>