记录下vite+vue3下 Scss主题配置的过程
- 创建Scss文件 _theme.scss
// 处理样式,遍历主题map
@mixin themeify {
@each $theme-name, $theme-map in $themes {
//!global 把局部变量提升为全局变量
$theme-map: $theme-map !global;
//判断html的data-theme的属性值#{}是sass的插值表达式 //& sass嵌套里的父容器标识 @content是混合器插槽,像vue的slot
[data-theme='#{$theme-name}'] & {
@content;
}
}
}
//声明一个根据Key获取颜色的function
@function themed($key) {
@return map-get($theme-map, $key);
}
// 获取颜色
@mixin bgColor($color) {
@include themeify {
background: themed($color) !important;
}
}
//获取字体颜色
@mixin textColor($color) {
@include themeify {
color: themed($color) !important;
}
}
//获取边框颜色
@mixin borderColor($color) {
@include themeify {
border-color: themed($color);
}
}
后面的@mixin 可根据需要添加
- 创建文件_common.scss 用于存放不同主题下的样式变量,引入theme文件
@import 'theme';
$themes: (
light: (
btn-bg: radial-gradient(circle, #0950e0 0%, #8ea6e2 100%),
btn-text: white
),
dark: (
btn-bg: #1c1f2d,
btn-text: white
)
);
- 将_common.scss 引入到global.scss
@import 'common';
- 配置vite.config.js
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "./src/style/scss/global.scss";',
javascriptEnabled: true
}
}
}
- 在App.vue onMounted 方法中设置document data-theme 属性,后面可根据用户的设置 在状态管理跟 localStorage中保存 获取后用户设置赋值从而改变整体样式
onMounted(() => {
document.documentElement.setAttribute('data-theme','light')
})
- 使用方式 使用@include 方法名(变量名)
<style lang="scss" scoped>
.login {
@include bgColor('btn-bg');
@include textColor('btn-text');
}
</style>
到此就结束了 后续主要就是在_common.scss文件中定义变量 然后页面上样式使用变量 根据用户切换主题 data-theme 属性就发生了变化 对应的变量颜色也就不一样了