vue开发后台项目需要实现换肤功能,所以找了一个解决方案
换肤实例
普通html实现换肤效果
App.vue代码
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
name: "app",
mounted() {
this.changeSkin();
},
methods: {
// 换肤
changeSkin() {
let theme = localStorage.getItem("theme");
if (!theme) {
window.document.documentElement.setAttribute("data-theme", "blue");
} else {
window.document.documentElement.setAttribute("data-theme", theme);
}
},
},
};
</script>
<style lang="scss">
#app {
width: 100%;
height: 100%;
}
</style>
src/views/Home.vue 代码
<template>
<div class="Home">
<div class="left"></div>
<div class="right">
<div class="top">
<span @click="changeSkin('blue')">blue</span>
<span @click="changeSkin('red')">red</span>
<span @click="changeSkin('yellow')">yellow</span>
<span @click="changeSkin('green')">green</span>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
// 选中的主题
themeId: "",
// 主题数据
themeList: ["blue", "red", "yellow", "green"],
};
},
mounted() {
if (localStorage.getItem("theme")) {
this.themeId = localStorage.getItem("theme");
} else {
this.themeId = "blue";
}
},
methods: {
// 换肤
changeSkin(mode) {
if (!mode) {
window.document.documentElement.setAttribute("data-theme", "blue");
localStorage.setItem("theme", "blue");
} else {
window.document.documentElement.setAttribute("data-theme", mode);
localStorage.setItem("theme", mode);
}
},
},
};
</script>
<style lang="scss" scoped>
.Home {
width: 100%;
height: 100%;
display: flex;
.left {
width: 200px;
margin-right: 5px;
@include Theme(); // 这里是引用混入函数
}
}
</style>
创建文件 src/assets/css/scss.scss
$white: #ffffff;
$yellow: #f4ea2a;
$green: #5fefa9;
$blue: #4475F7;
$red: #ff3d3d;
@mixin Theme {
[data-theme="blue"] & {
background-color: $blue;
.colorx {
color: $red;
}
}
[data-theme="red"] & {
background-color: $red;
}
[data-theme="yellow"] & {
background-color: $yellow;
}
[data-theme="green"] & {
background-color: $green;
}
}
vue.config.js sass 配置
const webpack = require('webpack');
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? '' : '/',
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-px2rem')({ //配置项,详见官方文档
remUnit: 100
}), // 换算的基数
]
},
sass: {
// 根据自己样式文件的位置调整
prependData: `@import "@/assets/css/scss.scss";`
}
}
},
}
可结合element ui动态更换主题色使用。