• This is the 13th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Functional component

We can mark a component as functional when it doesn’t need state (that is, reactive data), doesn’t need any lifecycle scenarios, and just accepts props to display the component.

functional: true.Copy the code

Because functional components are just functions, the rendering overhead is much lower.

Prior to 2.3.0, if a functional component wanted to receive a prop, the props option was required. In versions 2.3.0 and above, you can omit the props option, and attributes on all components are automatically resolved implicitly to prop.

To compensate for the lack of instances, the Render function provides a second argument, context, as the context. Context contains the following fields:

  • Props: Objects that provide all prop
  • Slots: a function that returns an object containing all slots (non-scoped)
  • ScopedSlots: (2.6.0+) An object that exposes the incoming scope slots. Normal slots are also exposed as functions.
  • Data: The entire data object passed to the component as the second parameter to createElement
  • Parent: reference to the parent component
  • An object containing all event listeners registered by the parent component for the current component. This is an alias for data.on.
  • Injections: (2.3.0+) If the Inject option is used, then the object contains attributes that should be injected.
  • Children: An array of VNode children, containing all non-scoped and non-named slots.

slots() VS children

Example 1:

<base-level :level="1" @click="handleClick">

  <template v-slot:header>
    <div>I am a head</div>
  </template>

  <div>div</div>
  <p>p</p>
  <template>template</template>

</base-level>
Copy the code

The result of slots() is:

{
  default: [<div>div</div>.<p>p</p>, template],
  header: [<div>I am a head</div>]}Copy the code

The results of children are:

[<div>div</div>.<p>p</p>, template]
Copy the code

Example 2:

<base-level :level="1" @click="handleClick">

  <template v-slot:header>
    <div>I am a head</div>
  </template>

  <template v-slot:default>
    <div>div</div>
  </template>

  <p>p</p>
  <template>template</template>

</base-level>
Copy the code

The result of slots() is:

{
  default: [<div>div</div>].header: [<div>I am a head</div>]}Copy the code

The results of children are:

[<div>div</div>.<p>p</p>, template]
Copy the code

Template-based functional components

In version 2.5.0 and above, if you use single-file components, template-based functional components can be declared as follows:

<template functional>
</template>
Copy the code

The last

If it is helpful to you, I hope to give you a 👍 comment/collection/three even!

Bloggers are honest and answer questions for free ❤