一、创建theme.css文件
:root[theme='light']{
--bgColor:#f0eeee;
--cardColor:white;
--cardLine:#f0eeee;
--font_1: #333;
--font_2: #555;
--font_3: #777;
--font_4: #777;
--textColor:#071418;
--titleColor:#071418;
}
:root[theme='dark']{
--bgColor:#071418;
--cardColor:#222429;
--cardLine:#071418;
--font_1: #f5f0f0;
--font_2: #5a5a5a;
--font_3: #777;
--font_4: #777;
--textColor:#777;
--titleColor:#777;
}
二、App.vue中引入css
<template>
<div>
<router-view/>
</div>
</template>
<script>
export default{
name:'myApp',
}
</script>
<style>
@import url('../src/assets/css/reset.css');
@import url('../src/assets/css/media.css');
@import url('../src/assets/css/common.css');
@import 'element-ui/lib/theme-chalk/display.css';
</style>
四、使用该css文件中的颜色
.cardColor {
background-color: var(--cardColor);
border: none;
color: var(--font_2);
margin-bottom: 20px;
}
五、切换主题的组件中
<template>
<div class="header-container">
<nav class="header-nav" ref="head_nav">
<el-row :gutter="24">
<el-col :xl="12" :lg="8" :md="6" :sm="8" :xs="14">
<div class="register_login">
<li>
<i @click="changeDark()" v-show="isSunny" class="head-i el-icon-sunny"></i>
<i @click="changeLight()" v-show="isMoon" class="head-i el-icon-moon"></i>
</li>
<li @click="goLogin()">登录</li>
<li @click="goRegister()">注册</li>
</div>
</el-col>
</el-row>
</nav>
</div>
</template>
<script>
export default{
name:'myHead',
data(){
return {
isSunny: false,
isMoon:false,
}
},
created() {
let theme = localStorage.getItem('theme') ? JSON.parse(localStorage.getItem('theme')) : 'light'
document.documentElement.setAttribute('theme', theme)
localStorage.setItem('theme',JSON.stringify(theme))
if(theme=='light'){
this.isSunny = true
this.isMoon = false
}else{
this.isSunny = false
this.isMoon = true
}
},
methods:{
changeLight() {
document.documentElement.setAttribute('theme', 'light')
localStorage.setItem('theme', JSON.stringify('light'))
this.isSunny = true
this.isMoon = false
},
changeDark() {
document.documentElement.setAttribute('theme', 'dark')
localStorage.setItem('theme', JSON.stringify('dark'))
this.isSunny = false
this.isMoon = true
},
}
}
</script>