Vue v-slot 指令
实例
使用 v-slot 指令把 'Hello!' 消息发送到 <slot-comp> 组件内的 'bottomSlot'。
<slot-comp v-slot:bottomSlot>'Hello!'</slot-comp>
定义与用法
v-slot 指令用于将内容定向到命名的 slot。
v-slot: 的简写为 #。
v-slot 指令还可以用于从 范围slot 接收数据,这是通过在子组件中使用 v-bind 提供的。
v-slot 可以用于组件,也可以用于内置的 <template> 元素。
当我们想将内容分配给组件中的多个 slot 时,v-slot 用于 <template> 元素。
更多实例
实例 1
在 <template> 元素上使用 v-slot 将内容分配给同一组件中的两个不同 slot。
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="/example/vue/img_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 将内容定向到默认 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 从 范围slot 接收数据。
App.vue:
<slot-comp v-slot:"dataFromSlot"><h2>{{ dataFromSlot.lclData }}</h2></slot-comp>