一、普通用法,哪个组件要用就在哪里引入
xxx.vue
<template>
<svg-icon name="iphone" color="pink" width="100px" height="100px"></svg-icon>
</template>
<script setup lang="ts">
import SvgIcon from '@/components/SvgIcon/index.vue'
</script>
二、全局注册组件,其他组件中只需要直接使用即可
main.ts
import SvgIcon from '@/components/SvgIcon/index.vue'
app.component('SvgIcon', SvgIcon);
这样在其他组件中不需要引入就可以直接用了
xxx.vue
<svg-icon><svg-icon>
三、自定义插件注册全局组件
跟第二种方法的区别是,不需要在main.ts中一个个引入所有组件
main.ts
import gloablComponent from '@/components';
app.use(gloablComponent);
src/components/index.ts
import SvgIcon from './SvgIcon/index.vue';
import Pagination from './Pagination/index.vue' //假如还有一个分页组件的话
import type { App, Component } from 'vue';
const components: { [name: string]: Component } = { SvgIcon,Pagination };
export default {
install(app: App) {
Object.keys(components).forEach((key: string) => {
app.component(key, components[key]);
})
}
}
在其他组件中直接使用
xxx.vue
<Pagination></Pagination>
<svg-icon></svg-icon>