vue3中如何全局注册组件app.component()

94 阅读1分钟

如果同时传递一个组件名字符串及其定义,则注册一个全局组件;如果只传递一个名字,则会返回用该名字注册的组件 (如果存在的话)。

1.创建组件(以面包屑为例子)

文件路径:components/breadcrumb/index.vue

<template>
    <a-breadcrumb class="container-breadcrumb">
        <a-breadcrumb-item>
            <icon-apps />
        </a-breadcrumb-item>
        <a-breadcrumb-item v-for="item in items" :key="item">
            <a-link v-if="typeof item === 'object'" :href="item.path">
            {{ item.label }}
            </a-link>
            <template v-else>
            {{ item }}
            </template>
        </a-breadcrumb-item>
    </a-breadcrumb>
</template>

<script setup>
import { defineProps } from 'vue';
const props = defineProps({
  items: {
      type: Array,
      default: () => [],
    },
})
</script>

2.组件封装成插件

文件路径:components/index.js

把 components 中的一些组件进行全局注册 提供插件方式

import Breadcrumb from './breadcrumb/index.vue';
import ResizeVideoUrl from './resizeVideoUrl/index.vue';
export default {
    install(vue){
        // Vue.component('组件名字',组件配置对象)
        Vue.component('Breadcrumb',Breadcrumb),
        Vue.component('ResizeVideoUrl', ResizeVideoUrl);
    }
}

3.引用注册

文件:main.js 引用且注册

import globalComponents from '@/components';

app.use(globalComponents)

4.使用组件

在 vue 页面中使用 使用全局组件,无需引用