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>
,但我们想控制内容应该出现在哪个 <slot>
中,我们需要给插槽命名,并使用 v-slot
将内容发送到正确的位置。
示例
为了能够区分插槽,我们给它们起了不同的名字。
SlotComp.vue
:
<h3>Component</h3>
<div>
<slot name="topSlot"></slot>
</div>
<div>
<slot name="bottomSlot"></slot>
</div>
现在我们可以使用 v-slot
在 App.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>
运行示例 »
在 <template> 中使用 v-slot
如你所见,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-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>
运行示例 »