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

Solve the problem of insufficient docker disk space

After the server where Docker is located has been...

jQuery custom magnifying glass effect

This article example shares the specific code of ...

HTML Basics Must-Read - Comprehensive Understanding of CSS Style Sheets

CSS (Cascading Style Sheet) is used to beautify H...

MySQL 8.X installation tutorial under Windows

I had been using MySQL 5.7 before, but because My...

Detailed tutorial on installing and using Kong API Gateway with Docker

1 Introduction Kong is not a simple product. The ...

Summary of four ways to loop through an array in JS

This article compares and summarizes four ways of...

Historical Linux image processing and repair solutions

The ECS cloud server created by the historical Li...

MySQL 8.0.15 winx64 installation and configuration method graphic tutorial

This article shares the installation and configur...

MySQL slow query log configuration and usage tutorial

Preface MySQL slow query log is a function that w...

Using zabbix to monitor the ogg process (Linux platform)

The ogg process of a database produced some time ...

Why MySQL does not recommend using subqueries and joins

To do a paginated query: 1. For MySQL, it is not ...

JavaScript deshaking and throttling examples

Table of contents Stabilization Throttling: Anti-...