基于最新的vue: 3.2.13,element-plus: 2.2.2
- 创建global目录,在此处可以引入一些需要全局注册的插件,比如element-plus,将需要使用的组件在全局注册一次
- element文件夹下的index.ts代码,将需要的组件在此处导入,注册组件
import type { App } from "vue"; //导入App类型
import "element-plus/theme-chalk/base.css"; //导入基础样式
import { ElButton } from "element-plus"; //所需组件在这里引入
const components = [ElButton]; //将组件放入数组
export default function (app: App): void { //导出一个函数,遍历数组,批量注册组件
for (const component of components) {
app.component(component.name, component); //全局注册组件
}
}
- global文件下的index.ts文件,作为所有插件的统一出口
import type { App } from "vue";
import registerElement from "./element";
export function registerApp(app: App): void {
app.use(registerElement);
}
- main.ts中注册
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import { registerApp } from "./global"; //导入统一的插件出口
const app = createApp(App);
registerApp(app); //调用函数,使用插件
app.use(router);
app.use(store);
app.mount("#app");
- 按需引入组件需要的样式 可参考官方文档:element-plus.gitee.io/zh-CN/guide…
- 这里使用官方文档推荐的unplugin-element-plus插件即可
yarn add unplugin-element-plus -D - 在vue.config.js中,配置插件
const { defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: {
plugins: [
require("unplugin-element-plus/webpack")({
// options
})
]
}
});