一:vue3项目创建
二:antdv安装
三:scss安装
四:tailwind安装
参考官网:https://www.tailwindcss.cn/docs/guides/vite#vue
五:新增全局主题配置(constant.scss)
$borderRadius: 4px;
$bg: #fff;
// 所有主题样式
$light: (
bgColor: #fff,
color: #333
);
$dark: (
bgColor: #333,
color: #fff
);
$theme: null;
@mixin themeify {
// theme list
$themes: light, dark;
@each $theme in $themes {
[data-theme=#{$theme}] & {
@if $theme =='light' {
$theme: $light !global;
} @else {
$theme: $dark !global;
}
@content
}
}
}
//声明一个根据Key获取颜色的function
@function themed($key) {
@return map-get($theme, $key);
}
//获取背景颜色
@mixin bgColor($color) {
@include themeify {
background-color: themed($color) !important;
}
}
//获取字体颜色
@mixin textColor($color) {
@include themeify {
color: themed($color) !important;
}
}
body {
@include bgColor('bgColor');
@include textColor('color');
}
五:vite配置文件(vite.config.ts)配置全局主题文件
export default defineConfig({
plugins: [
vue(),
vueJsx(),
Components({
resolvers: [
AntDesignVueResolver({
importStyle: false // css in js
})
]
})
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
open: true,
port: 8888
},
css: {
preprocessorOptions: {
// 全局样式引入
scss: {
// 文件路径,注意最后需要添加 ';'
additionalData: '@import "@/assets/constant.scss";',
javascriptEnabled: true
}
}
}
})
六:配合pinia实现全局读取(stores/theme.ts)
import { defineStore } from 'pinia'
const theme = window.matchMedia('(prefers-color-scheme: dark)').matches // 深色
export const useThemeStore = defineStore('theme', {
state: () => ({
defaultMode: theme ? 'dark' : 'light', // dark light
themeToken: {}
}),
actions: {
// 切换模式
changeMode() {
this.defaultMode = this.defaultMode === 'dark' ? 'light' : 'dark'
}
}
})
七:App.vue配置暗色/亮色模式以及antdv预设主题使用
<script setup lang="ts">
import { RouterView } from 'vue-router'
import { theme } from 'ant-design-vue'
import { computed, ref } from 'vue'
import { useThemeStore } from '@/stores/theme'
const themeStore = useThemeStore()
const darkMode = themeStore.defaultMode
console.log(darkMode)
const themeConfig = computed(() => {
// 主题配置
return {
algorithm: darkMode === 'light' ? theme.defaultAlgorithm : theme.darkAlgorithm
}
})
window.document.documentElement.setAttribute('data-theme', darkMode)
</script>
<template>
<a-style-provider hash-priority="high">
<a-config-provider :theme="themeConfig">
<RouterView />
</a-config-provider>
</a-style-provider>
</template>
<style scoped lang="scss"></style>
注意:
<a-style-provider hash-priority="high">xxx<a-style-provider>
如果使用了taidwind需要此包裹组件;查看官方解释