Vue3+Sass实现主题色切换
·
前言
本篇简单快捷进行快速的主题色切换配置
默认您已经安装了Sass并配置好了相关Sass的相关内容
1.添加Sass主题配色
在Vue项目中新增一个theme.scss文件,并进行各个主题色的配置,这里我仅使用亮色和暗色两种主题色进行演示。
//theme.scss文件
$light: (
primary: #42b983,// 亮色主题主色
secondary: #23fa,// 亮色辅助色
text-primary: #333, // 亮色文本
text-neutral: #666, // 亮色中性文本
);
$dark: (
primary: #111315, // 暗色主题主色
secondary: #adff4d,// 暗色辅助色
text-primary: #fff, // 暗色文本
text-neutral: #bbb, // 暗色中性文本
);
2.将 Sass 主题变量转换为可动态切换的 CSS 变量
新增一个index.scss文件,用于将sass变量转换成css变量(这里使用两个文件仅是用于将主题和函数进行解耦,可将函数放置在同一文件内)
//index.scss文件
@import './theme.scss';
//使用mixin函数将sass变量转换为css变量的格式 (例如:--theme-primary: #42b983)
@mixin theme-vars($theme, $prefix: 'theme-') {
@each $key, $value in $theme {
--#{$prefix}#{$key}: #{$value};
}
}
//将所有的sass变量放置在.light-theme和.dark-theme的类名下,以便这两个类名内的元素使用对应的变量
.light-theme {
@include theme-vars($light);
}
.dark-theme {
@include theme-vars($dark);
}
3.引入Sass全局样式
在配置好scss文件后,将文件设置为全局样式,这样在Vue文件中使用scoped时仍然可以使用主题色。在入口文件main.ts内引入scss文件。
//main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import '@/style/theme/index.scss' //引入文件
//....其余的main.ts代码
4.在Vue中使用变量
在使用scss的主题色变量之前,需要将页面的最根级元素设置相对于的类名,在第2步骤当中,所有的由sass生成的css样式都放置在.light-theme和.dark-theme类名内。
4.1为根级节点设置主题色类名
获取根级节点document.documentElement,并添加class类名
//test.vue文件
<script lang="ts" setup>
onMounted(() => {
setThemeClass('dark')
})
// 设置根元素主题类名
const setThemeClass = (theme: Theme) => {
const root = document.documentElement
root.classList.add(`${theme}-theme`)
console.log(root.classList)
}
</script>
4.2在Style中使用主题色变量
在style样式中,直接通过var(--theme-变量名)的方式即可直接使用对应的颜色
<template>
<div class="page-box"></div>
</template>
<script setup lang="ts">
onMounted(() => {
setThemeClass('dark')
})
// 设置根元素主题类名
const setThemeClass = (theme: Theme) => {
const root = document.documentElement
root.classList.add(`${theme}-theme`)
console.log(root.classList)
}
</script>
<style lang="scss" scoped>
.page-box{
width:100px;
height:100px;
background-color: var(--theme-secondary); // 使用辅助色背景
}
</style>
5.主题更换
主题色更换的原理就是改变根级元素的类名,我这里默认给了暗色dark作为初始化颜色。
可根据自己的项目情况本地存储用户设置的主题色或与浏览器主题保持同步。
<template>
<div class="page-box">
<!-- 主题切换按钮 -->
<button @click="toggleTheme" class="theme-btn">切换主题(当前:{{ currentTheme }})</button>
</div>
</template>
<script setup lang="ts">
// 定义主题类型
type Theme = 'light' | 'dark'
const currentTheme = ref<Theme>('light')
// 初始化主题
onMounted(() => {
currentTheme.value = 'dark'
setThemeClass(currentTheme.value)
})
// 设置根元素主题类名
const setThemeClass = (theme: Theme) => {
const root = document.documentElement
root.classList.remove('light-theme', 'dark-theme')
root.classList.add(`${theme}-theme`)
console.log(root.classList)
}
// 切换主题
const toggleTheme = () => {
currentTheme.value = currentTheme.value === 'light' ? 'dark' : 'light'
setThemeClass(currentTheme.value)
}
</script>
<style lang="scss" scoped>
.page-box{
width:100px;
height:100px;
background-color: var(--theme-secondary); // 使用辅助色背景
}
</style>更多推荐

所有评论(0)