vue项目有换肤的需求,那么如何换肤呢。一般是准备两份黑白版UI设计色调。采用
CSS var()
函数自定义变量属性调用。
定义一个名为 "--background" 的属性,然后使用 var(--background) 函数调用该属性
。思路就是,
切换皮肤时,切换不同的不同皮肤的自定义属性值。默认黑色背景,每次切换皮肤,存储本地存储,刷新后皮肤保持一致
。
1、theme.less
theme-b.less
:root {
--background: #000;
}
theme-w.less
:root.white{
--background: #fff;
}
theme.less
@import "theme-b.less";
@import "theme-w.less";
2、引用theme.less
App.vue
<template>
<div id="app">
<img ref="test" alt="Vue logo" src="./assets/logo.png">
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
@import "./less/theme.less";
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
height: 100vh;
background: var(--background);
}
</style>
3、皮肤切换
theme.js
const theme = window.theme || {};
theme.changeTheme = function (type) {
switch (type) {
case 'white':
document.documentElement.classList.add('white');
break;
case 'black':
document.documentElement.classList.remove('white');
break;
default:
document.documentElement.classList.remove('white');
break;
}
}
// 初始化判断皮肤
theme.detectSelectedTheme = function () {
const type = localStorage.getItem('theme') || '';
localStorage.setItem('theme', type);
theme.changeTheme(type);
}
export default theme;
main.js
import Vue from 'vue'
import App from './App.vue'
import theme from './utils/theme'
// 初始化皮肤
theme.detectSelectedTheme();
Vue.prototype.themeUtils = theme;
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
App.vue
<template>
<div id="app">
<img ref="test" alt="Vue logo" src="./assets/logo.png">
<button @click="changeTheme()">切换</button>
</div>
</template>
<script>
export default {
name: 'App',
methods:{
changeTheme(){
const type = localStorage.getItem('theme') == 'white' ? 'black' : 'white';
localStorage.setItem('theme', type)
this.themeUtils.changeTheme(type)
}
}
}
</script>
<style>
@import "./less/theme.less";
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
height: 100vh;
background: var(--background);
}
</style>