svg全局组件
<template>
<div>
<svg :style="{ width, height }">
<use :xlink-href="prefix + name" :fill="color"></use>
</svg>
</div>
</template>
<script setup>
defineProps({
width: {
type: 'String',
default: "16px"
},
height: {
type: 'String',
default: "16px"
},
prefix: {
type: 'String',
default: "#icon-"
},
name: {
type: 'String',
default: ""
},
color: {
type: 'String',
default: ""
}
})
</script>
<style lang="scss" scoped></style>
自定义插件
// 自定义插件:用于注册全局组件
import SvgIcon from "./SvgIcon/index.vue";
// 所有需要注册为全局的组件(下面对象使用了简写)
const allGlobalComponent = { SvgIcon };
// Object.keys 遍历获取对象中所有的key,返回的结果为数组
const allComponentKeys = Object.keys(allGlobalComponent);
console.log(allComponentKeys);
// 对外暴露插件对象
export default {
// 这里的方法必须为install,因为会把 app 应用实例注入进来
install(app) {
// 注册全局组件
allComponentKeys.forEach((key) => {
app.component(key, allGlobalComponent[key]);
});
},
};
最后在入口文件中使用自定义插件
// 引入自定义插件进行注册全局组件
import globalComponent from "@/components/index.js";
const app = createApp(App);
// 安装自定义插件
app.use(globalComponent);