记录-解决element-plus自动引入后ElLoading、ElMessage、ElNotification、ElMessageBox样式丢失的问题

问题描述

vue3项目中使用element-plus自动引入遇到ElLoading、ElMessage、ElNotification、ElMessageBox样式丢失的问题。


原因分析:

废话少说,以ElLoading为例,下面是使用的代码片段:

import { ElLoading } from "element-plus";
console.log(ElLoading);
ElLoading.service({
    lock: true,
    text: "在努力获取数据啦~"
});

打印了一下 ElLoading 是否正常导入,发现是没问题的。
解决element-plus自动引入后遇到ElLoading、ElMessage、ElNotification、ElMessageBox样式丢失的问题

然后F12看了一下样式,发现class正常插入,但是没样式,也就是样式丢了。
解决element-plus自动引入后遇到ElLoading、ElMessage、ElNotification、ElMessageBox样式丢失的问题

ElMessage、ElNotification、ElMessageBox样式丢失测试图:

在这里插入图片描述


解决方案:

方案一: 在打包的入口文件或者依赖树中引入对应组件的样式,可以写在main.ts或者main.js里,按自己需求引入

// main.ts/main.js
import "element-plus/theme-chalk/el-loading.css";
import "element-plus/theme-chalk/el-message.css";
import "element-plus/theme-chalk/el-notification.css";
import "element-plus/theme-chalk/el-message-box.css";

方案二:使用unplugin-element-plus对使用到的组件样式进行按需导入

 npm i unplugin-element-plus -D

不同打包工具对应不同配置:

  • vite
// vite.config.ts
import ElementPlus from 'unplugin-element-plus/vite'

export default {
  plugins: [
    ElementPlus({
      // options
    }),
  ],
}
  • Vue CLI
// vue.config.js
module.exports = {
  configureWebpack: {
    plugins: [
      require('unplugin-element-plus/webpack')({
        // options
      }),
    ],
  },
}
  • Webpack
// webpack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-element-plus/webpack')({
      // options
    }),
  ],
}
  • Rollup
// rollup.config.js
import ElementPlus from 'unplugin-element-plus/rollup'

export default {
  plugins: [
    ElementPlus({
      // options
    }),
  ],
}
  • esbuild
// esbuild.config.js
import { build } from 'esbuild'

build({
  plugins: [
    require('unplugin-element-plus/esbuild')({
      // options
    }),
  ],
})

方案三:全局完整引入element-plus的样式文件
方案可行,但是对于按需的目的来说,不是很推荐

// main.ts/main.js
import "element-plus/dist/index.css";
只是测了这几个,别的组件可能也有类似问题,同理解决即可。
  • 28
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值