Vue v-slot 指令


示例

使用v-slot指令来指示“Hello!”消息发送到 <slot-comp> 组件内的命名槽“bottomSlot”。

<slot-comp v-slot:bottomSlot>'Hello!'</slot-comp>
运行示例 »

请参阅下面的更多示例。


定义和用法

这个v-slot指令用于将内容定向到指定的槽。

简写为v-slot:#

这个v-slot指令还可以用于从作用域槽接收数据,通过使用提供v-bind在子组件中。

v-slot可以用在组件上,也可以用在内置上<template>元素。

v-slot用于<template>当我们想要将内容分配给组件中的多个插槽时,可以使用元素。


更多示例

示例1

使用v-slot<template>元素将内容分配给同一组件中的两个不同插槽。

App.vue:

<template>
  <h1>App.vue</h1>
  <p>The component has two slots, and the template element is used to assign content to both.</p>
  <slot-comp>
    <template v-slot:topSlot>
      <div>
        <p>Tigers are beautiful!</p>
        <img src="tiger.svg" alt="tiger" width="100">
      </div>
    </template>
    <template v-slot:bottomSlot>
      <div>
        <p>Whales can be very big</p>
      </div>
    </template>
  </slot-comp>
</template>

SlotComp.vue:

<template>
  <hr>
  <h3>Component</h3>
  <slot name="topSlot"></slot>
  <slot name="bottomSlot"></slot>
</template>
运行示例 »

示例2

使用v-slot将内容定向到默认插槽。

SlotComp.vue:

<h3>Component</h3>
<div>
  <slot></slot>
</div>
<div>
  <slot name="bottomSlot"></slot>
</div>

App.vue:

<h1>App.vue</h1>
<p>The component has two div tags with one slot in each.</p>
<slot-comp v-slot:default>'Default slot'</slot-comp>
运行示例 »

示例3

使用v-slot:简写#

App.vue:

<h1>App.vue</h1>
<p>The component has two div tags with one slot in each.</p>
<slot-comp #topSlot>'Hello!'</slot-comp>

SlotComp.vue:

<h3>Component</h3>
<div>
  <slot name="topSlot"></slot>
</div>
<div>
  <slot name="bottomSlot"></slot>
</div>
运行示例 »

示例4

使用v-slot从作用域槽接收数据。

App.vue:

<slot-comp v-slot:"dataFromSlot">
  <h2>{{ dataFromSlot.lclData }}</h2>
</slot-comp>
运行示例 »

相关页面

Vue教程:Vue 老虎机

Vue教程:范围插槽

Vue教程:Vue 组件

Vue教程:Vue v 槽

Vue参考:Vue <slot> 元素

Vue参考:Vue $slots 对象