Home > Web Front-end > Vue.js > body text

How to implement the automatic registration function of vue3 global components

WBOY
Release: 2023-05-13 08:13:05
forward
2945 people have browsed it

vue3 global component automatic registration

Step one: Create file

You need to create a folder under src/components to store the encapsulated public components (I named it coms here)

You need to create a js file under src/components to store and register imported components (I named it Index.js here)

How to implement the automatic registration function of vue3 global components

The second step : Write function

to create a folder in coms and put the component into this folder. The name of this folder is the name of the component we are going to register.

How to implement the automatic registration function of vue3 global components

Write the following tool function in Index.js:

// 全局组件注册 需要到coms这个目录下注册
 
export default {
    install(app) {
        const req = require.context('./coms', true, /\.vue$/);
        req.keys().forEach((item) => {
            const defaultObj = req(item).default;
 
            let name = item.split('/')[1];
            // console.log('name', name);
            app.component(name, defaultObj);
        });
    }
};
Copy after login

Note: I did not use defaultObj.__file to get the file path here because of production The __file attribute will be deleted in the environment, which will result in the following error

How to implement the automatic registration function of vue3 global components

Step 3: Import the file

Import the tool function in main.js and hang it Load into the app

import coms from '@/components/Index'; //全局组件注册
app.use(coms);
Copy after login

Step 4: Use globally

At this step, you can use the file name we defined as the component name globally.

How to implement the automatic registration function of vue3 global components

#ps: vue2 is actually pretty much the same, just change app.use() to Vue.use()

Supplement: Vue3 registration global Component

For example, if a component is used very frequently and is used on almost every page, it can be encapsulated into a global component

1. Register a single global component

Introduced in main.ts Our component follows createApp(App). Remember not to put it after mount. This is a chain call. Use

and then call component. The first parameter is the component name and the second parameter is the component instance.

import { createApp } from 'vue'
import App from './App.vue'
import './assets/css/reset/index.less'
import Card from './components/Card/index.vue'
createApp(App).component('Card',Card).mount('#app') 
//.component('Card',Card)就是注册全局组件 (‘自定义键名',组件名)
Copy after login

Usage method

You can use it directly on other vue pages without introducing it

<template>
 <Card></Card>
</template>
Copy after login

2. Batch registration of global components

When you encounter many global components that need to be registered, you can Define the middleware, let the middleware complete the component registration, and then introduce and use this middleware in main.js

Create a new index.ts in src/componentsUse To import all components that need to be globally registered

How to implement the automatic registration function of vue3 global components

##✨: If you are using

JS you can delete the type check

import type { Component } from &#39;vue&#39; //import type 是用来协助进行类型检查和声明的,在运行时是完全不存在的。

import SvgIcon from &#39;./SvgIcon/index.vue&#39;

// ✨如果使用的是 JS 可以删除类型校验

const components: {

  [propName: string]: Component //字面量类型,每个属性值类型为组件的类型

} = {

  SvgIcon

}

export default components
Copy after login

2 . Import

in main.ts

✨Use a loop here to register each global component

import { createApp } from &#39;vue&#39;

import ElementPlus from &#39;element-plus&#39;

import &#39;element-plus/dist/index.css&#39; // 基于断点的隐藏类 Element 额外提供了一系列类名,用于在某些条件下隐藏元素

import App from &#39;./App.vue&#39;

import router from &#39;./router&#39;

import { store, key } from &#39;./store&#39;

import globalComponent from &#39;@/components/index&#39; //引入需要注册的全部组件

const app = createApp(App)

app.use(store, key).use(router).use(ElementPlus)

// 注册全局的组件 (对所有需要注册的组件进行遍历并注册)

for (const componentItme in globalComponent) {

  app.component(componentItme, globalComponent[componentItme])

}

app.mount(&#39;#app&#39;) //需要注册完组件后才挂载
Copy after login

3. If you use

TSWriting, you also need to create a components.d.ts in the same directory as main.ts to handle component introduction errors and add component type prompts

How to implement the automatic registration function of vue3 global components

import SvgIcon from &#39;@/components/SvgIcon/index.vue&#39;

//要扩充@vue/runtime-core包的声明

declare module &#39;@vue/runtime-core&#39; {

  export interface GlobalComponents { //这里扩充"ComponentCustomProperties"接口

    SvgIcon: typeof SvgIcon

  }

}
Copy after login
4. Finally, just import it directly

How to implement the automatic registration function of vue3 global components

The above is the detailed content of How to implement the automatic registration function of vue3 global components. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template