Article directory
1. What is a slot?
When we use it <slot>
as a placeholder, the parent component can display it 传递的内容
at the location of the placeholder, improving the use of the component 灵活性
.
2. Slot content
The parent component passes some to the child components 模板片段
, allowing the child components to render those fragments in their components.
example:
<!-- 父组件 -->
<FancyButton>
<!-- 插槽内容 -->
click me
</FancyButton>
<!-- 子组件 -->
<button class="fancy-btn">
<!-- 插槽出口 -->
<slot></slot>
</button>
Rendering result:
<button class="fancy-btn">Click me!</button>
Explanation: <slot>
The element is an element 插槽出口 (slot outlet)
that indicates 插槽内容 (slot content)
where the element provided by the parent component will be rendered.
Schematic:
3. Rendering scope
The slot content is accessible 父组件的数据作用域
because the slot content itself is 父组件模板中
defined.
example:
<!-- message 是父组件的数据 -->
<FancyButton>{
{ message }}</FancyButton>
Explanation: Expressions in the parent component template can only be accessed 父组件的作用域
; expressions in the child component template can only be accessed 子组件的作用域
.
4. Default content
Default content can be specified for a slot when nothing is provided externally.
example:
<!-- 父组件 -->
<SubmitButton />
<!-- 子组件 -->
<button type="submit">
<slot>
<!-- 默认内容 -->
Submit
</slot>
</button>
Rendering result:
<button type="submit">Submit</button>
5. Named slots
<slot>
Elements can have a special one attribute name
assigned to each slot 唯一的 ID
to determine what content is to be rendered at each location:
example:
<!-- 子组件 -->
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
<!-- 父组件 -->
<BaseLayout>
<template #header>
<h1>Here might be a page title</h1>
</template>
<template #default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
<template #footer>
<p>Here's some contact info</p>
</template>
</BaseLayout>
Explanation: This type name
of slot with is called 具名插槽 (named slots)
. 没有提供 name
will <slot> 出口
be implicitly named “default”
. v-slot
There is a corresponding abbreviation #
, so <template v-slot:header>
it can be abbreviated as <template #header>
, which means "pass this part of the template fragment into the subcomponent header 插槽中
".
Schematic:
6. Scope slot
The content of the slot set by the parent component requires the data in the child component domain. To do this, we need to have the child component provide a portion of its data to the slot when rendering.
example:
<!-- 子组件 -->
<div>
<slot :text="greetingMessage" :count="1"></slot>
</div>
<!-- 父组件 -->
<MyComponent v-slot="slotProps">
{
{ slotProps.text }} {
{ slotProps.count }}
</MyComponent>
Explanation: The subcomponent passed into the slot props
as v-slot
the value of the directive can be accessed in the expression within the slot.
Schematic: