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 Components
Vue 教程:Vue v-slot
Vue 参考: Vue <slot> 元素
Vue 参考: Vue $slots 对象