解决在nuxt3中,修改 elemnt-plus 修改全局主题色的问题

2,203 阅读1分钟

一.版本

"nuxt": "3.0.0-rc.4",
"element-plus": "^2.2.17",
"vue": "^3.2.37"

二.解决思路

1.在vite+vue3+element-plus中,修改主题色很容易。 只需要新建一个文件夹,然后写入如下代码:

$--colors: (
  "primary": (
    "base":#3870E6,
  ),
  "success": (
    "base": #21ba45,
  ),
  "warning": (
    "base": #f2711c,
  ),
  "danger": (
    "base": #db2828,
  ),
  "error": (
    "base": #db2828,
  ),
  "info": (
    "base": #42b8dd,
  ),
);

// You should use them in scss, because we calculate it by sass.
// comment next lines to use default color
@forward "element-plus/theme-chalk/src/common/var.scss" with (
  // do not use same name, it will override.
  $colors: $--colors,
);

// if you want to import all
// @use "element-plus/theme-chalk/src/index.scss" as *;
// You can comment it to hide debug info.
// @debug $--colors;

// import dark theme
@use "element-plus/theme-chalk/src/dark/css-vars.scss" as *;

2.然后在vite.config.js文件中引入即可

  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "~/styles/element/index.scss" as *;`,
      },
    },
  },

3.但是我在nuxt3中却无法在nuxt.config.js中引入使用。
可能是现在的版本不兼容这种写法。
我尝试过直接引入到APP.vue,或者放到nuxt插件文件夹下的plugins/element-plus.ts也是无法生效的。

在nuxt.config.js中无法生效
export default defineNuxtConfig({
css['~~/public/element/index.scss']
})

4.最终,我使用了直接修改style样式的方法

第一种:

1.在app.vue文件的onMounted生命周期里,直接修改dom里面的style样式

onMounted( () => {
  document.body.style.setProperty('--el-color-primary', '#1788FF');
});
三个参数:.setProperty('样式名称','样式属性','样式权重');

第二种:

2.直接在.vue文件内部的 style 标签内修改,

body {
  --el-color-primary:#ff0000 !important;
}

.el-select {
  // 修改的是选中focus状态下select选择框的颜色
  --el-select-input-focus-border-color: #fff !important;
}