自定义插件注册全局组件(以使用svg组件为例)

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);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值