一、安裝依賴
npm i scss sass-loader -D
這里其實(shí)在vue create demo
時(shí)候就可以選擇性安裝的
npm i style-loader@1.3.0 -D
注意版本,不要用最新2.0的氢烘,我測(cè)試發(fā)現(xiàn)沒(méi)法use
二、配置
因?yàn)槲矣玫?code>vue-cli4家厌,這里需要?jiǎng)?chuàng)建一個(gè)vue.config.js
文件播玖,然后直接粘貼下面內(nèi)容
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]
})
}
}
三、編寫(xiě)樣式
將樣式全部提取出來(lái)
比如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
//導(dǎo)入公共樣式
@import "main";
$bg-light: #ffffff;
$bg-grey: #9a9a9a;
$bg-dark: #000000;
單個(gè)主題配置文件src/asserts/css/light.scss
@import "act";
.home{
background: $bg-light;
}
四饭于、主題色的導(dǎo)入
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中配置有多少個(gè)主題樣式就寫(xiě)幾個(gè)
五蜀踏、初始化主題
在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
,根據(jù)需要選擇
六掰吕、切換主題色
<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