Vue v-slot

我们需要v-slot参考指令命名槽

命名槽允许更好地控制内容在子组件模板中的放置位置。

命名槽可用于创建更灵活和可重用的组件。

使用前v-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>
运行示例 »

通过组件中的两个插槽,我们可以看到内容只是出现在两个位置。


v 槽和命名槽

如果我们有多个<slot>在一个组件中,但我们想控制在哪个组件中<slot>内容应该出现,我们需要命名插槽并使用v-slot将内容发送到正确的位置。

示例

为了能够区分插槽,我们给插槽起了不同的名称。

SlotComp.vue:

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

现在我们可以使用v-slotApp.vue将内容定向到正确的插槽。

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: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更清楚地表明该内容属于默认槽。

示例

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>
运行示例 »

<模板> 中的 V 型槽

正如你所看到的v-slot指令可以用作组件标记中的属性。

v-slot也可以用在<template>标签将大部分内容定向到某个特定位置<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 型槽简写 #

简写为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>
运行示例 »

Vue练习

通过练习测试一下

练习:

如果组件“CompOne”有两个插槽,如下所示:

<slot name="headerSlot"></slot>

<slot name="mainSlot"></slot>

我们如何从 App.vue 直接发送文本“动物很有趣!”进入“CompOne”中的“mainSlot”插槽?

<slot-comp >
    Animals are interesting!
</slot-comp>

开始练习