This is the 10th day of my participation in the August Text Challenge.More challenges in August

In this article we will look at how to use the built-in component and what we need to be aware of when using it. We mentioned it a little bit in the back of Vue3 directive (9), but let’s take a closer look.

How to use

Renders a “meta-component” as a dynamic component. Determines which component is rendered based on the value of is. The value of is is a string that can be either an HTML tag name or a component name. It is worth noting that if they are components we want to make sure they are registered.

Use variables to reference components

Suppose a variable is currentComponent, which can be a component name or the component itself.

The usage method is as follows:

<component :is="currentComponent"></component>
Copy the code

Component name

Given that the registered component is my-Component, currentComponent=” my-Component “, the dynamic component renders my-Component.

Component itself

We define a variable that is a component as follows:

setup() {
    const todoList = ref({
        template: ` 
      
  • {{item}}
`
}) return { todoList } } Copy the code

We leave currentComponent=”todoList” to render the component itself, no registration required.

Use $options to reference the component

With $options, you can render registered components or components passed in by prop as follows:

<component :is="$options.components.child"></component>
Copy the code

Where child is a variable, change it to the name of any component you want to render.

Use strings to reference components

Given that the registered component is my-component, we can reference the component directly with strings like this:

<component :is="'my-component'"></component>
Copy the code

Render native HTML elements

We can render native HTML elements using the built-in Component component as follows:

<component :is="'h1'"></component>
Copy the code

The ternary operation

When using the built-in Component component, the value of is can be the result of a ternary operation, as follows:

<component :is=" isNativeHTML ? 'h1' : 'my-component' "></component>
Copy the code

IsNativeHTML, which indicates whether it is a native HTML element, is Boolean.

conclusion

  1. The value of is is a string.

  2. Dynamic components are usually used for functions such as login and registration switch, article reading switch, etc. In a word, use component appropriately according to your own needs.

For more articles, the portal has opened: Look back at the Vue3 catalogue!