一、安装依赖
npm i scss sass-loader -D
这里其实在vue create demo
时候就可以选择性安装的
npm i style-loader@1.3.0 -D
注意版本,不要用最新2.0的,我测试发现没法use
二、配置
因为我用的vue-cli4
,这里需要创建一个vue.config.js
文件,然后直接粘贴下面内容
module.exports = {
chainWebpack: config => {
const scss = config.module
.rule('scss')
.toConfig()
const theme = {
...scss.oneOf[3],
test: /\.scss$/
}
theme.use = [...theme.use]
theme.use[0] = {
loader: 'style-loader',
}
config.module
.rule('scss')
.merge({
oneOf: [theme]
})
}
}
三、编写样式
将样式全部提取出来
比如src/asserts/css/main.scss
用于存放全部公共样式
html, body, #app{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.home{
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
提取的差异化配置src/asserts/css/act.scss
//导入公共样式
@import "main";
$bg-light: #ffffff;
$bg-grey: #9a9a9a;
$bg-dark: #000000;
单个主题配置文件src/asserts/css/light.scss
@import "act";
.home{
background: $bg-light;
}
四、主题色的导入
let obj = {}
let current = null
const theme = {
dark () {
if (!obj.dark) {
obj.dark = import('../assets/css/dark.scss');
}
return obj.dark
},
light () {
if (!obj.light) {
obj.light = import('../assets/css/light.scss');
}
return obj.light
},
grey () {
if (!obj.grey) {
obj.grey = import('../assets/css/grey.scss');
}
return obj.grey
}
}
async function setTheme (name) {
if (theme[name]) {
let styles = await theme[name]()
if (current) {
current.unuse();
}
styles.use();
current = styles
}
}
export default setTheme
这里只需要在theme中配置有多少个主题样式就写几个
五、初始化主题
在app.vue
import setTheme from './common/theme'
export default {
name: 'App',
created() {
if (window.sessionStorage.getItem('bg') === 'light') {
setTheme('light');
} else if (window.localStorage.getItem('bg') === 'dark') {
setTheme('dark')
} else {
setTheme('grey')
}
}
}
我用的是sessionStorage
,根据需要选择
六、切换主题色
<template>
<div class="home">
<el-button @click="changeBg('light')">light</el-button>
<el-button type="info" @click="changeBg('grey')">grey</el-button>
<el-button type="danger" @click="changeBg('dark')">dark</el-button>
</div>
</template>
<script>
import setTheme from '../common/theme'
export default {
name: 'Home',
methods: {
changeBg(color) {
setTheme(color);
window.sessionStorage.setItem('bg', color);
}
}
}
</script>
参考文章
https://blog.csdn.net/han_ling_sha/article/details/103968580