vue+scss主题切换,换肤(通过setAttribute)
2023-02-09 本文已影响0人
新世界的冒险
image.png
动画.gif
动画.gif
1、新建theme.scss文件
// 主题1
$background-color-black: #0D2865;
$background-color-white: #eba5a5;
$font-color-white: #f1ff77;
$font-color-black: #ea4141;
// 主题2
$background2-color-black: #75084f;
$background2-color-white: #998a00;
$font2-color-white: #1e3dea;
$font2-color-black: #ffffff;
2、新建mixin.scss文件,进行主题封装
@import './theme.scss';
@mixin bg_color($color) {
background-color: $color;
[data-theme="black"] & {
background-color: $background-color-black;
}
[data-theme="white"] & {
background-color: $background-color-white;
}
}
@mixin font_color($color) {
color: $color;
[data-theme="black"] & {
color: $font-color-black;
}
[data-theme="white"] & {
color: $font-color-white;
}
}
@mixin bg2_color($color) {
background-color: $color;
[data-theme="black"] & {
background-color: $background2-color-black;
}
[data-theme="white"] & {
background-color: $background2-color-white;
}
}
@mixin font2_color($color) {
color: $color;
[data-theme="black"] & {
color: $font2-color-black;
}
[data-theme="white"] & {
color: $font2-color-white;
}
}
3、操作展示文件test.vue
<template>
<div class="about">
<button @click="toggoleTheme">点击变色</button>
<div class="changebox">这是一个变色盒子</div>
<div class="changebox2">这是一个变色盒子2</div>
</div>
</template>
<script>
export default {
data() {
return {
theme: 'black'
}
},
methods: {
// 当前分为white主题和black主题进行切换
toggoleTheme() {
this.theme = this.theme === 'white' ? 'black' : 'white'
// 通过setAttribute设置data-theme主题进行切换
document.documentElement.setAttribute('data-theme', this.theme );
}
}
}
</script>
<style lang="scss">
@import '@/assets/mixin.scss';
.changebox {
width: 200px;
height: 200px;
@include bg_color($background-color-black);
@include font_color($font_color-black);
}
.changebox2 {
width: 200px;
height: 200px;
@include bg2_color($background2-color-black);
@include font2_color($font2_color-black);
}
</style>