之前写的这篇博文《使用Vite搭建Vue3+ElementUI-Plus项目过程》描述了快速搭建Vite+Vue3+ElementUI Plus的项目,其中对自定义主题也进行了说明,当时自己测试也是没问题的,具体的vite.config.js配置文件如下:

import { defineConfig } from 'vite'
import path from 'path'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'

// https://vitejs.dev/config/
export default defineConfig({
  //一下为新添加的内容
  resolve: {
    alias: {
      '~/': `${path.resolve(__dirname, 'src')}/`,
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "~/style.scss" as *;`,
      },
    },
  },
  //一下为之前的配置内容
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver({
	      importStyle: 'sass'
	  )],
    }),
    ElementPlus({
      useSource: true,
    })
  ]
})

其中style.scss是自定义的主题文件。但是项目页面多了后有时候出现主题不生效的问题,一开始没在意,但这次是彻底不生效了,查了官网的案例,对比了自己的,感觉没问题呀,最终在这片博文中找到了答案:vue3 使用element-plus按需引入插件时,自定义element主题颜色。最后只在一个地方增加了一行代码,问题解决

AutoImport({
    resolvers: [ElementPlusResolver({
        importStyle: 'sass'
    })],
}),

在AutoImport中也要加上importStyle这个属性,据说是不加的话会导致ElMessage等组件的样式会覆盖我门自定义的,最终vite.config.js

import { defineConfig } from 'vite'
import path from 'path'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'

// https://vitejs.dev/config/
export default defineConfig({
  base: '/',
  resolve: {
    alias: {
      '~/': `${path.resolve(__dirname, 'src')}/`,
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "~/style.scss" as *;`,
      },
    },
  },
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver({
        importStyle: 'sass'
      })],
    }),
    Components({
      resolvers: [ElementPlusResolver({
        importStyle: 'sass'
      })],
    }),
    ElementPlus({
      useSource: true
    })
  ]
})
Logo

前往低代码交流专区

更多推荐