关于在VUE3中使用element-plus的踩坑记录
关于在VUE3、VITE中使用element-plus的踩坑记录
按需引入组件 这里会遇到的问题数样式消失,下面是官网说明
借助 babel-plugin-import,我们可以只引入需要的组件
1 $ npm install babel-plugin-import -D
将 babel.config.js 修改为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 module.exports = { plugins: [ [ "import", { libraryName: 'element-plus', customStyleName: (name) => { // 由于 customStyleName 在配置中被声明的原因,`style: true` 会被直接忽略掉, // 如果你需要使用 scss 源文件,把文件结尾的扩展名从 `.css` 替换成 `.scss` 就可以了 return `element-plus/lib/theme-chalk/${name}.css`; }, }, ], ], };
在 main.js 中写入以下内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { createApp } from 'vue' import { ElButton, ElSelect } from 'element-plus'; import App from './App.vue'; const app = createApp(App) app.component(ElButton.name, ElButton); app.component(ElSelect.name, ElSelect); /* or * app.use(ElButton) * app.use(ElSelect) */ app.mount('#app')
当然这是不适用于vite中的,在vite中需要引入一下插件
1 npm i vite-plugin-style-import -D
在vite.config.js文件中做如下新增
1 2 3 4 5 6 7 8 9 10 11 12 plugins: [ vue(), styleImport({ // 样式按需导入 libs: [{ libraryName: 'element-plus', esModule: true, resolveStyle: (name) => { return `element-plus/lib/theme-chalk/${name}.css`; } }] }) ]
这样就可以随心所欲的按需求映入插件了!😏
国际化 这边的话也遇到了问题就是那官网的方法并不能显示中文,先看下官网配置
1 2 3 4 5 6 7 import { createApp } from 'vue' import { ElButton, locale } from 'element-plus' import lang from 'element-plus/lib/locale/lang/zh-cn' import 'dayjs/locale/zh-cn' locale(lang) createApp(App).component(ElButton.name, ElButton)
后来发现是之前的插件引起的问题、所以单独修改了下配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 plugins: [ vue(), styleImport({ // 样式按需导入 libs: [{ libraryName: 'element-plus', esModule: true, resolveStyle: (name) => { if (name !== 'locale') return `element-plus/lib/theme-chalk/${name}.css`; else return `element-plus/lib/theme-chalk/el-table.css` } }] }) ]
然后就能正常显示中文了
欢迎指正 欢迎大佬指正!