在命令行,安装sass、sass-loader
npm install --save-dev sass、sass-loader
在src/scss文件夹下,创建index.scss、mixin.scss、variable.scss文件
在main.js导入,全局使用
import { createApp } from 'vue'
import App from './App.vue'
import "./scss/index.scss";
createApp(App).mount('#app')
创建2个组件使用
创建button.vue
<script >
export default {
methods:{
changeSkin(themeName){
//切换主题
window.document.documentElement.setAttribute("data-skin",themeName);
}
},
created(){
//默认主题
window.document.documentElement.setAttribute("data-skin",'skin1');
},
}
</script>
<template>
<div>
<button @click="changeSkin('skin1')">切换皮肤1</button>
<button @click="changeSkin('skin2')">切换皮肤2</button>
</div>
</template>
创建head.vue
<template>
<div id="poe-content">
<div class="poetry-title">楚宫怨二首·其一</div>
<div class="poetry-author">李涉〔唐代〕</div>
<p>十二山晴花尽开,楚宫双阙对阳台。</p>
<p>细腰争舞君沉醉,白日秦兵天下来。</p>
</div>
</template>
在variable.scss中定义2个主题配置
// $background-color: bisque;
// $poetry-title-color: darkblue;
// $font-size: 15px;
// $text-decoration-color: dodgerblue;
$themes: (
skin1:( //主题1
background-color: bisque,
poetry-title-color: darkblue,
font-size: 15px,
text-decoration-color: dodgerblue,
),
skin2:( //主题2
background-color: rgba(196, 229, 255, 0.605),
poetry-title-color: rgba(0, 139, 14, 0.546),
font-size: 20px,
text-decoration-color: rgba(255, 30, 150, 0.342),
),
) !default;
在mixin.scss定义用到的方法、混合
@mixin currentTheme($themes){ //获取当前主题的全部属性
@each $key,$value in $themes {
[data-skin='#{$key}'] &{
// $currentZhemeName:$key !global;
$currentZhemeObj:$value !global; //获取当前主题的全部属性
@content ;//相当于vue的插槽,把代码放@content这里运行
}
}
};
@function getKeyValue($key){ //获取主题内,某个属性的值
@return map-get($currentZhemeObj, $key)
};
在index.scss存放除了变量、方法、混合外的样式
@import "./variable.scss";
@import "./mixin.scss";
#poe-content{
display: flex;
flex-direction: column;
justify-items: center;
align-items: center;
@include currentTheme($themes){
background-color:getKeyValue('background-color');
};
.poetry-title{
font-weight: bold;
@include currentTheme($themes){
font-size:calc(getKeyValue('font-size') + 5px);
};
@include currentTheme($themes){
color:getKeyValue('poetry-title-color');
};
// color: $poetry-title-color;
}
.poetry-author{
font-weight: lighter;
@include currentTheme($themes){
color:getKeyValue('poetry-title-color');
};
@include currentTheme($themes){
font-size:getKeyValue('font-size');
};
}
p{
text-align: left;
text-decoration-line: underline;
text-decoration-style: wavy;
@include currentTheme($themes){
text-decoration-color:getKeyValue('text-decoration-color');
};
@include currentTheme($themes){
font-size:calc(getKeyValue('font-size') + 2px);
};
// font-size: calc(#{$font-size} + 2px);
}
}
结果图
![](https://i-blog.csdnimg.cn/blog_migrate/7086cc7bb7f02115f1fdca6bb3088405.png)
![](https://i-blog.csdnimg.cn/blog_migrate/2bac75574ea944d71092008489047e9f.png)