Holle! 我是Boy~,今天我给大家分享以下关于 Vue3注册全局组件 使用方法,下面是官网方法链接,可以点击哦 !!!
全局组件:顾名思义,全局都可以使用的组件, 组件在当前 Vue 应用中全局可用。下面我们来看一下怎么注册全局组件。
我们以项目创建后的 components 下的 HelloWorld.vue 为例 ----
创建 vite 项目:yarn create vite
main.js
// main.js
import { createApp } from "vue";
import App from "./App.vue";
// 1. 引入 HelloWorld 组件
import HelloWorld from "./components/HelloWorld.vue";
const app = createApp(App);
// 2. 注册全局组件("自定义键名",组件名)
const _h = app.component("HelloWorld", HelloWorld);
// 3. 挂载全局组件
app.use(_h);
app.mount("#app");
使用:
<template>
<HelloWorld msg="Vite + Vue" />
</template>
如果我们需要多个组件,注册成全局组件。如果使用上面的方法就有点太麻烦。
下面我们封装优化一下:在 components 文件夹下创建 index.js
(1) index.js
// 1.引入组件 --- 注意路径要正确
import HelloWorld from "./HelloWorld.vue";
import Icon from "./Icon.vue"
// 2. 使用 Vue3 提供的 install() 方法
export const com = {
install(app) {
// app.component("组件名称", 组件配置对象)
app.component("HelloWorld", HelloWorld);
app.component("Icon", Icon)
},
};
(2)main.js
import { createApp } from "vue";
import App from "./App.vue";
// 1. 引入 index.js
import { com } from "./components/index"
const app = createApp(App);
// 2. 挂载全局
app.use(com);
app.mount("#app");
使用:
<template>
<HelloWorld msg="Vite + Vue" />
<Icon iconName="icon-a-Group788" />
</template>
如果对 您 有帮助 不妨点个赞关注一下(强老板大气),后续我也会发布一些对你有帮助的文章 !!!