Vue按需引入注册UI以及自定义组件的封装

1.单文件global注册自定义组件的封装
import A from "../view/A.vue";
import B from "../view/B.vue";
const components = { A, B };

export default {
  install(Vue) {
    for (let k in components) {
      Vue.component(k, components[k]);
    }
  },
};
在main.js中引入使用
import LocalComponents from "./global";
createApp(App).use(LocalComponents).mount("#app");

2.按需引入注册UI组件的封装 (比如elementPlus的组件以及图标)
(1)单文件register-element.ts (组件库)
import { App } from 'vue'
import 'element-plus/theme-chalk/base.css'
import 'element-plus/theme-chalk/index.css'
import {
  ElForm,
} from 'element-plus'

const components = [ElForm]

export default function (app: App): void {
  for (const component of components) {
   app.component(component.name, component)
  }
}
(2)单文件register.elementIcon.ts (图标库)
import { App } from 'vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

export default function (app: App) {
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
  }
}

(3)文件抽离,在index.ts中全部注册函数
import { App } from 'vue'
import registerElement from './register-element'
import registerElementIcon from './register-elementIcon'

export function globalRegister(app: App): void {
  registerElement(app)
  registerElementIcon(app)
}

(4)最后在main.js中局部引入-- 封装后的element-plus
import { globalRegister } from "./global";
createApp(App).use(globalRegister).mount("#app");
posted @ 2022-12-27 13:31  SKa-M  阅读(251)  评论(0编辑  收藏  举报