How to automatically import Vue components on demand

How to automatically import Vue components on demand

In Vue, we can use components through global components and local registration

Global Registration

Create global components through app.component

import { createApp } from 'vue'
import HelloWorld from './components/HelloWorld'

const app = createApp({})

// Globally register a component named hello-wolrd app.component('hello-wolrd', HelloWorld);

Once we register the component globally, we can use it anywhere: <hello-world/>

It is worth noting that global registration will make Vue lose TypeScript support. Vue 3 has a PR that expands the interface of global components. Currently, Volar already supports this usage. We can add TypeScript support for all game components by adding a components.d.ts file to the root directory.

declare module 'vue' {
  export interface GlobalComponents {
    HelloWorld: typeof import('./src/components/HelloWorld.vue')['default']
  }
}

Partial Registration

We can import the vue component directly from the file.

In a single file component (SFC)

<template>
  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components:
    HelloWorld
  }
}
</script>

In JSX

import HelloWorld from './components/HelloWorld.vue'
export default {
  name: "item",
  render(){
    return (
      <HelloWorld msg="Welcome to Your Vue.js App"/>
    )
  }
}

Locally registered components are not accessible in other components and are not available in their parent or child components, so you need to reintroduce and register the component in each place where it is used.

import HelloWorld from './components/HelloWorld.vue'

But this way of importing components directly has another advantage. If the imported component uses typescript, we can get smart prompts and type checking functions in the component without any plugins.

Local automatic registration

It can be seen that the advantages of local registration are obvious, but we need to import it repeatedly every time we use it. However, if you have many components, your component registration code may look lengthy. We can use unplugin-vue-components to automatically import components on demand. It will import components on demand, but there is no need to import and register components.

This plugin will automatically generate a components.d.ts for the components used to get TypeScript support.

Install the plugin

vite

// vite.config.ts
import Components from 'unplugin-vue-components/vite'

export default defineConfig({
  plugins: [
    Components({ /* options */ }),
  ],
})

Rollup

// rollup.config.js
import Components from 'unplugin-vue-components/rollup'

export default {
  plugins: [
    Components({ /* options */ }),
  ],
}

webpack

// webpack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-vue-components/webpack')({ /* options */ })
  ]
}

We can then use the component in our template as usual and it will automatically do the following transformation

<template>
  <div>
    <HelloWorld msg="Hello Vue 3.0 + Vite" />
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

Convert to

<template>
  <div>
    <HelloWorld msg="Hello Vue 3.0 + Vite" />
  </div>
</template>

<script>
import HelloWorld from './src/components/HelloWorld.vue'

export default {
  name: 'App',
  components:
    HelloWorld
  }
}
</script>

By default, it will search for components in the src/components directory. We can customize the component directory through the dirs parameter. For other configurations, refer to github.com/antfu/unplu…

Comparison of different solutions

Global Registration Partial Registration unplugin-vue-components
TypeScript support Define the components.d.ts file Default support Automatically generate components.d.ts file
Component Scope Global Local Local
How to use Use after global registration Use after local registration Use after adding the plugin

About component names

There are two ways to define component names:

Using kebab-case:

Vue.component('my-component-name', { /* ... */ })
When defining a component using kebab-case (dash-separated names),
You must also use kebab-case when referencing the custom element, for example <my-component-name> .

Use PascalCase

Vue.component('MyComponentName', { /* ... */ })
When defining a component using PascalCase,
You can use either nomenclature when referencing the custom element.
This means that both <my-component-name> and <MyComponentName> are acceptable.
Note, however, that only kebab-case is valid when used directly in the DOM (i.e. non-string templates).

Therefore, we generally recommend that components use the kebab-case naming method.

refer to

v3.cn.vuejs.org/guide/comp…

v3.cn.vuejs.org/guide/types…

github.com/antfu/unplu…

Summarize

This is the end of this article on how to automatically introduce Vue components on demand. For more information about automatically introducing Vue components on demand, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Vue's method of introducing subcomponents
  • Detailed explanation of how to introduce elementUI components into vue projects
  • Vue's method of introducing all public components at one time in a concise and clear manner
  • Detailed explanation of how to create a new Vue project and introduce the component Element
  • Solve the problem of Vue introducing subcomponent errors
  • How to import, register and use components in batches in Vue

<<:  MySQL database constraints and data table design principles

>>:  vmware virtual machine ubuntu18.04 installation tutorial

Recommend

Import csv file into mysql using navicat

This article shares the specific code for importi...

How to start the spring-boot project using the built-in linux system in win10

1. Install the built-in Linux subsystem of win10 ...

How to configure multiple tomcats with Nginx load balancing under Linux

The methods of installing nginx and multiple tomc...

Vue3+TypeScript encapsulates axios and implements request calls

No way, no way, it turns out that there are peopl...

JS implements sliding up and down on the mobile terminal one screen at a time

This article shares with you the specific code of...

Solution to the 404/503 problem when logging in to TeamCenter12

TeamCenter12 enters the account password and clic...

How to install ElasticSearch on Docker in one article

Table of contents Preface 1. Install Docker 2. In...

The concept and characteristics of MySQL custom variables

A MySQL custom value is a temporary container for...

Detailed tutorial on installing pxc cluster with docker

Table of contents Preface Preliminary preparation...

Implementation of socket options in Linux network programming

Socket option function Function: Methods used to ...

Solution to the problem that MySQL commands cannot be entered in Chinese

Find the problem Recently, when I connected to th...

JavaScript timer to achieve seamless scrolling of pictures

This article shares the specific code of JavaScri...

JavaScript css3 to implement simple video barrage function

This article attempts to write a demo to simulate...