Vue 换肤设计

如何在vue项目中设置夜间模式

夜间模式:顾名思义也就是去反色而已

简述:
	普通项目中,从localStorage中拿取当前样式的名称,选择加载动态加载css,
 然后head标签添加link节点即可。
	在本项目中,因为使用的是vue,所以稍微改变一下,但是原理都是一样的,
都要有一个中间件,也就是存放在localStorage中的themeName值。

具体步骤

  1. localStorage中添加值 themeName
  2. 在设置界面添加按钮, 去切换themeName
  3. 在main.js读取localStorage的themeName, 保存到实例中prototype中,这样所有组件template就能用了
  4. 在每个组件, 根据 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'}"
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值