vue项目中实现换肤(包括颜色、样式、图片)

使用vue-cli 搭建的项目,页面中很多模块都用组件实现的,当初每个组件的样式都写在了自己的style里面,本来想每个组件提取两个css文件,根据localstorage中存储的值来判断切换不同的css;

if(localStorage.getItem("colorstatus")=='neon'||localStorage.getItem("colorstatus")==null){
localStorage.setItem("colorstatus",'dark');
}else{
localStorage.setItem("colorstatus",'neon');
}

然后通过判断

colorstatus 来  require('../assets/css/neon-a.css')或 require('../assets/css/dark-a.css')

切换可以,但是第二次点击切换皮肤按钮,两个css已经都加载上了,所以必须在require加载之前将上次加载的css删除,无奈我只知道require 引入,不会删除,为了实现效果,只能把页面中所有组件的class名称写两套,一套深色皮肤,一套浅色皮肤;即nav-neon,和nav-dark 根据当前颜色来切换class,当然是比较复杂,如果有更好方法,希望推荐;

当然其中也用到了组件传值,将目前的colorstatus 传给其他组件,而且我们要有初始的皮肤,所以也要考虑页面刚加载的情况

初始化:

data () {
return {

bcolor:localStorage.getItem("colorstatus"),

}

},

created(){
this.unloadInfo()
},

unloadInfo(){
this.$emit('load-info',this.lists[0].manager);
this.name = this.lists[0].manager;
this.$emit('color-info',localStorage.getItem("colorstatus"));
if(localStorage.getItem("colorstatus")=='neon'||localStorage.getItem("colorstatus")==null){   如果localstorage 为neon 或null(第一次使用)
this.message = require('../../assets/message.jpg');
this.config = require('../../assets/config.jpg');
this.GM = require('../../assets/images/GM.png');
this.personal = require('../../assets/images/personal-insurance.png');图片切换
this.bank = require('../../assets/images/bank-insurance.png');
this.operation = require('../../assets/images/operation.png');
}else{
this.message = require('../../assets/newimage/message2.png');
this.config = require('../../assets/newimage/config2.png');
this.GM = require('../../assets/newimage/GM2.png');
this.personal = require('../../assets/newimage/personal-insurance2.png');
this.bank = require('../../assets/newimage/bank-insurance2.png');
this.operation = require('../../assets/newimage/operation2.png');
}


},

判断皮肤变化进行切换

mounted(){
  this.$watch('bcolor', function(newVal, oldVal){
this.bcolor = newVal;
if(newVal=='neon'||newVal==null){
this.message = require('../../assets/message.jpg');
this.config = require('../../assets/config.jpg');
this.GM = require('../../assets/images/GM.png');
this.personal = require('../../assets/images/personal-insurance.png');
this.bank = require('../../assets/images/bank-insurance.png');
this.operation = require('../../assets/images/operation.png');
}else{
this.message = require('../../assets/newimage/message2.png');
this.config = require('../../assets/newimage/config2.png');
this.GM = require('../../assets/newimage/GM2.png');
this.personal = require('../../assets/newimage/personal-insurance2.png');
this.bank = require('../../assets/newimage/bank-insurance2.png');
this.operation = require('../../assets/newimage/operation2.png');
}
});
    },

样式颜色切换(更换class)

个险

当然也可以复制一份html.写两套样式,通过v-if 控制切换html,从而达到div切换,样式切换效果;

类似这个,有些笨拙和麻烦,有更好方法,还望指教;

你可能感兴趣的:(vue项目中实现换肤(包括颜色、样式、图片))