Home  >  Article  >  Web Front-end  >  What is the implementation principle of Vue3 slot Slot?

What is the implementation principle of Vue3 slot Slot?

王林
王林forward
2023-05-24 09:28:481674browse

Vue’s official definition of slot

Vue implements a set of content distribution APIs. The design of this API is inspired by the Web Components specification draft and will <slot></slot> Elements serve as outlets for hosting distributed content.

What is Slot

So what exactly is Slot? Slot is actually a function that accepts the slot content passed by the parent component, then generates a VNode and returns it.

We generally use <slot></slot> This pair of tags accepts the content passed by the parent component. Then the final compilation of this pair of tags is a function that creates a VNode. , we can call it the function that creates the slot VNode.

// <slot></slot>标签被vue3编译之后的内容
export function render(_ctx, _cache, $props, $setup, $data, $options) {
  return _renderSlot(_ctx.$slots, "default")
}

We can clearly see that the <slot></slot> tag becomes a function called _renderSlot after it is compiled by Vue3.

How to use slots

To use slots, parent-child components must exist.

Assume that the parent component has the following content:

<todo-button>
  Add todo
</todo-button>

We use a todo-button child component in the parent component and pass Add todo's slot content.

todo-button sub-component template content

<button class="btn-primary">
  <slot></slot>
</button>

When the component is rendered, <slot></slot> will be replaced with "Add todo" .

Review the principle of component rendering

So what is the underlying principle? Before understanding the underlying principles of slots, we also need to review the operating principles of Vue3 components.

The core of the component is that it can produce a bunch of VNode. For Vue, the core of a component is its rendering function. The essence of mounting a component is to execute the rendering function and obtain the VNode to be rendered. As for data/props/computed, these are all used to provide data for the rendering function to generate VNode. The most important thing about the source service is the VNode finally produced by the component, because this is the content that needs to be rendered.

The initialization principle of the slot

When Vue3 encounters a VNode type of component, it will enter the component rendering process. The process of component rendering is to first create a component instance, and then initialize the component instance. When initializing the component instance, Slot-related content will be processed.

In the runtime-core\src\component.ts of the source code

What is the implementation principle of Vue3 slot Slot?

Initialize the related content of the component Slot in the function initSlots

So what does the initSlots function look like and what does it do?

runtime-core\src\componentSlots.ts

What is the implementation principle of Vue3 slot Slot?

First of all, we need to determine whether the component is a Slot component. Then how to determine whether the component is a Slot component? ? We first need to go back and take a look at the compiled code of the parent component above:

export function render(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_todo_button = _resolveComponent("todo-button")
  return (_openBlock(), _createBlock(_component_todo_button, null, {
    default: _withCtx(() => [
      _createTextVNode(" Add todo ")
    ], undefined, true),
    _: 1 /* STABLE */
  }))
}

We can see that the children content of the Slot component is an Object type, which is the following code:

{
    default: _withCtx(() => [
      _createTextVNode(" Add todo ")
    ], undefined, true),
    _: 1 /* STABLE */
}

Then When the VNode of this component is created, it will be judged whether its children are of type Object. If it is of type Object, then a Slot component tag will be attached to the shapeFlag of the VNode of the component.

If it is compiled through a template, it is the standard slot children, which has the _ attribute and can be placed directly on the component instance. slots Attributes.

If it is a slot object written by the user himself, then there is no _ attribute, so it needs to be normalized, go to normalizeObjectSlots.

If the user's behavior does not follow the specifications, then follow the normalizeVNodeSlots process.

Analyze the contents of the slot

Let’s first look at the compiled code of the subcomponent:

export function render(_ctx, _cache, $props, $setup, $data, $options) {
  return (_openBlock(), _createElementBlock("button", { class: "btn-primary" }, [
    _renderSlot(_ctx.$slots, "default")
  ]))
}

We also talked about it above<slot>&lt ;/slot></slot>After the tag is compiled by vue3, it becomes a function called _renderSlot.

What is the implementation principle of Vue3 slot Slot?

renderSlotThe function accepts five parameters, the first is the slot function object slots on the instance, the second is the name of the slot, that is, rendering the slot content to the specified location, the third is the props received by the slot scope, the fourth is the default content rendering function of the slot, and the fifth Not sure what it means yet.

Scope Slot Principle

Scope slot is a way for a child component to pass parameters to a parent component, allowing the slot content to access data only in the child component.

Subcomponent template

<slot username="coboy"></slot>

Compiled code

export function render(_ctx, _cache, $props, $setup, $data, $options) {
  return _renderSlot(_ctx.$slots, "default", { username: "coboy" })
}

Parent component template

<todo-button>
    <template v-slot:default="slotProps">
        {{ slotProps.username }}
    </template>
</todo-button>

Compiled code

export function render(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_todo_button = _resolveComponent("todo-button")
  return (_openBlock(), _createBlock(_component_todo_button, null, {
    default: _withCtx((slotProps) => [
      _createTextVNode(_toDisplayString(slotProps.username), 1 /* TEXT */)
    ]),
    _: 1 /* STABLE */
  }))
}

As mentioned above Through the renderSlot function, it can be simply summarized into the following code

export function renderSlots(slots, name, props) {
  const slot = slots[name]
  if (slot) {
    if (typeof slot === &#39;function&#39;) {
      return createVNode(Fragment, {}, slot(props))
    }
  }
}

slots is the slot content uploaded by the component instance, which is actually this content

{
    default: _withCtx((slotProps) => [
      _createTextVNode(_toDisplayString(slotProps.username), 1 /* TEXT */)
    ]),
    _: 1 /* STABLE */
}

name is default , then what slots[name] gets is the following function

_withCtx((slotProps) => [
      _createTextVNode(_toDisplayString(slotProps.username), 1 /* TEXT */)
])

slot(props) is obviously slot({ username: "coboy" }), which transfers the data in the child component to the parent component The contents of the slot are in.

具名插槽原理

有时我们需要多个插槽。例如对于一个带有如下模板的 <base-layout></base-layout> 组件:

<div class="container">
  <header>
    <!-- 我们希望把页头放这里 -->
  </header>
  <main>
    <!-- 我们希望把主要内容放这里 -->
  </main>
  <footer>
    <!-- 我们希望把页脚放这里 -->
  </footer>
</div>

对于这样的情况,<slot></slot> 元素有一个特殊的 attribute:name。通过它可以为不同的插槽分配独立的 ID,也就能够以此来决定内容应该渲染到什么地方:

<!--子组件-->
<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

一个不带 name 的 <slot></slot> 出口会带有隐含的名字“default”。

在向具名插槽提供内容的时候,我们可以在一个 <template></template> 元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称:

<!--父组件-->
<base-layout>
  <template v-slot:header>
    <h2>header</h2>
  </template>
  <template v-slot:default>
    <p>default</p>
  </template>
  <template v-slot:footer>
    <p>footer</p>
  </template>
</base-layout>

父组件编译之后的内容:

export function render(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_base_layout = _resolveComponent("base-layout")
  return (_openBlock(), _createBlock(_component_base_layout, null, {
    header: _withCtx(() => [
      _createElementVNode("h2", null, "header")
    ]),
    default: _withCtx(() => [
      _createElementVNode("p", null, "default")
    ]),
    footer: _withCtx(() => [
      _createElementVNode("p", null, "footer")
    ]),
    _: 1 /* STABLE */
  }))
}

子组件编译之后的内容:

export function render(_ctx, _cache, $props, $setup, $data, $options) {
  return (_openBlock(), _createElementBlock("div", { class: "container" }, [
    _createElementVNode("header", null, [
      _renderSlot(_ctx.$slots, "header")
    ]),
    _createElementVNode("main", null, [
      _renderSlot(_ctx.$slots, "default")
    ]),
    _createElementVNode("footer", null, [
      _renderSlot(_ctx.$slots, "footer")
    ])
  ]))
}

通过子组件编译之后的内容我们可以看到这三个Slot渲染函数

_renderSlot(_ctx.$slots, "header")

_renderSlot(_ctx.$slots, "default")

_renderSlot(_ctx.$slots, "footer")

然后我们再回顾一下renderSlot渲染函数

// renderSlots的简化
export function renderSlots(slots, name, props) {
  const slot = slots[name]
  if (slot) {
    if (typeof slot === &#39;function&#39;) {
      return createVNode(Fragment, {}, slot(props))
    }
  }
}

这个时候我们就可以很清楚的知道所谓具名函数是通过renderSlots渲染函数的第二参数去定位要渲染的父组件提供的插槽内容。父组件的插槽内容编译之后变成了一个Object的数据类型。

{
    header: _withCtx(() => [
      _createElementVNode("h2", null, "header")
    ]),
    default: _withCtx(() => [
      _createElementVNode("p", null, "default")
    ]),
    footer: _withCtx(() => [
      _createElementVNode("p", null, "footer")
    ]),
    _: 1 /* STABLE */
}

默认内容插槽的原理

我们可能希望这个 <button></button> 内绝大多数情况下都渲染“Submit”文本。为了将“Submit”作为备用内容,我们可以将它放在 <slot></slot> 标签内

<button type="submit">
  <slot>Submit</slot>
</button>

现在当我们在一个父级组件中使用 &lt;submit-button&gt;&lt;/submit-button&gt; 并且不提供任何插槽内容时:

&lt;submit-button&gt;&lt;/submit-button&gt;

备用内容“Submit”将会被渲染:

<button type="submit">
  Submit
</button>

但是如果我们提供内容:

<submit-button>
  Save
</submit-button>

则这个提供的内容将会被渲染从而取代备用内容:

<button type="submit">
  Save
</button>

这其中的原理是什么呢?我们先来看看上面默认内容插槽编译之后的代码

export function render(_ctx, _cache, $props, $setup, $data, $options) {
  return (_openBlock(), _createElementBlock("button", { type: "submit" }, [
    _renderSlot(_ctx.$slots, "default", {}, () => [
      _createTextVNode("Submit")
    ])
  ]))
}

我们可以看到插槽函数的内容是这样的

_renderSlot(_ctx.$slots, "default", {}, () => [
    _createTextVNode("Submit")
])

我们再回顾看一下renderSlot函数

renderSlot函数接受五个参数,第四个是插槽的默认内容渲染函数。

What is the implementation principle of Vue3 slot Slot?

再通过renderSlot函数的源码我们可以看到,

第一步,先获取父组件提供的内容插槽的内容,

在第二个步骤中,若父组件已提供插槽内容,则使用该插槽内容,否则执行默认的内容渲染函数以获取默认内容。

The above is the detailed content of What is the implementation principle of Vue3 slot Slot?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete