Vue v-slot
我们需要 v-slot 指令来引用命名的 slot。
命名 slot 可以更好地控制内容在子组件模板中的放置位置。
命名 slot 可以用于创建更灵活和可重用的组件。在使用 v-slot 和命名 slot 之前,让我们看看如果在组件中使用两个 slot 会发生什么:
实例
App.vue:
<h1>App.vue</h1><p>The component has two div tags with one slot in each.</p><slot-comp>'Hello!'</slot-comp>
SlotComp.vue:
<h3>Component</h3><div><slot></slot></div><div><slot></slot></div>
在一个组件中有两个 Slot(插槽)时,我们可以看到内容只是同时出现在两个位置。
v-slot 与命名 Slot
如果我们在一个组件中有多个 <slot>,但我们想控制内容应该出现在哪个 <slot> 中,我们需要命名 Slot 并使用 v-slot 将内容发送到正确的位置。
实例
为了能够区分插槽(slot),我们为插槽提供了不同的名称。
SlotComp.vue:
<h3>Component</h3><div><slot name="topSlot"></slot></div><div><slot name="bottomSlot"></slot></div>
现在我们可以在 App.vue 中使用 v-slot 将内容引导到正确的 slot。
App.vue:
<h1>App.vue</h1><p>The component has two div tags with one slot in each.</p><slot-comp v-slot:bottomSlot>'Hello!'</slot-comp>
默认 Slot
如果您有一个没有名称的 <slot>,那么对于标记有v-slot的组件,该 <slot> 将是默认的:default,或者没有标记有 v-slot 的组件。
要了解这是如何工作的,我们只需要在前面的实例中进行两个小的更改:
实例
SlotComp.vue:
<h3>Component</h3><div><slot name="topSlot"></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:bottomSlot>'Hello!'</slot-comp>
如前所述,我们可以使用默认值 v-slot:default 来标记内容,以便更清楚地表明内容属于默认 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>
<template> 中的 v-slot
正如您所看到的,v-slot 指令可以用作组件标记中的属性。
v-slot 也可以在 <template> 标签中使用,将内容的较大部分引导到某个 v-slot。
实例
App.vue:
<h1>App.vue</h1><p>The component has two div tags with one slot in each.</p><slot-comp><template v-slot:bottomSlot><h4>To the bottom slot!</h4><p>This p tag and the h4 tag above are directed to the bottom slot with the v-slot directive used on the template tag.</p></template><p>This goes into the default slot</p></slot-comp>
SlotComp.vue:
<h3>Component</h3><div><slot></slot></div><div><slot name="bottomSlot"></slot></div>
我们使用 <template> 标记将某些内容定向到某个 <slot>,因为 <template> 标签没有呈现,它只是内容的占位符。你可以通过检查构建的页面来看到这一点:你在那里找不到模板标记。
v-slot 简写
v-slot: 的简写为 #。
比如:
<slot-comp v-slot:topSlot>'Hello!'</slot-comp>
可以写为:
<slot-comp #topSlot>'Hello!'</slot-comp>
实例
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>