如何在vue项目中设置夜间模式
夜间模式:顾名思义也就是去反色而已
简述:
普通项目中,从localStorage中拿取当前样式的名称,选择加载动态加载css,
然后head标签添加link节点即可。
在本项目中,因为使用的是vue,所以稍微改变一下,但是原理都是一样的,
都要有一个中间件,也就是存放在localStorage中的themeName值。
具体步骤
- localStorage中添加值 themeName
- 在设置界面添加按钮, 去切换themeName
- 在main.js读取localStorage的themeName, 保存到实例中prototype中,这样所有组件template就能用了
- 在每个组件, 根据 themeName 加载不同的样式, 同时样式绑定( :class )
step1: localStorage中添加值 themeName?
首先在按钮页面的data和created中:
data() {
return {themeName:"light"};
},
created() {
this.themeName = localStorage.themeName
}
给夜间模式这个按钮(我这里是input)添加一个事件
@click="dealChange"
把当前的themeName值存放在localStorage中:
methods: {
dealChange(){
//选择这个按钮
var ipt = document.querySelector("input")
//判断按钮是否选中
if(ipt.checked){
//若选中,证明打开夜间模式,也就要把当前的themeName变为黑色属性,也就是dack属性
this.themeName = "dark"
//重新设置缓存themeName
localStorage.themeName = this.themeName
//刷新页面
location.reload()
}else{
this.themeName = "light"
localStorage.themeName = this.themeName
location.reload()
}
}
}
step2: localStorage中添加值 themeName?
因为我是用的按钮有checked值所以在 location.reload()页面刷新之后又变回原来的
关闭状态了,所以在mounted中对这个checked值进行了判断处理。
上述步骤已经添加进去了,因为input有自动关闭功能,所以要在dom加载时进行input按钮checked值的修改。(还是在按钮页面)
mounted() {
var ipt = document.querySelector("input")
if(this.themeName == "dark"){
ipt.setAttribute("checked","")
}else{
ipt.removeAttribute("checked")
}
}
step3: 在main.js读取localStorage的themeName, 保存到实例中prototype中,这样所有组件template就能用了?
我们在设置页面操作navbar.vue文件中的背景色,需要把themeName放在vue的原型对象中,所以,
在main.js中。
//加载保存的主题名
Vue.prototype.themeName = "light"
if(localStorage.themeName != undefined){
Vue.prototype.themeName = localStorage.themeName
}
在navbar.vue文件中:
<div class='navbar' :class="{'dark':themeName=='dark'}"> </div>
/* dark theme */
.navbar.dark {
background-color: #333;
border-bottom: 1px solid #eee;
color: #ccc;
}
step4: 在每个组件, 根据 themeName 加载不同的样式, 同时样式绑定( :class )?
想要修改哪个元素样式,只需要在css中设置:
元素类名.dark{
//样式
}
然后在此元素标签中绑定下面这个属性即可:
:class="{'dark':themeName=='dark'}"