在上一节中我们通过动态切换html中css的引用路径实现了vue中的换皮肤功能。但是这种方法有一个缺陷,那就是只能用css的语法来实现。这个缺陷在某些变态的需求下会增加我们很多工作量,因此本节中将介绍vue中另一种换皮肤的实现思路,用less语法实现换肤。
上节中讲过,想要达到换皮肤的目的无非就是替换掉样式文件,而一般项目中使用less都会在style标签中import样式文件。但是现在我们想要达到动态加载样式文件的效果,因此就不能使用import了,而需要使用另一种引入样式文件的方法require。也就是说在每一个想要根据所选皮肤更改样式的页面都使用require来动态加载样式文件。
- 在项目的main.js中的methods下新增_getLess方法用来根据当前所选皮肤获取样式文件,但是需要使用到mixin:
Vue.mixin({
computed: {
...mapGetters([
'templates'
]),
},
created() {
var theme = localStorage.theme;
if(theme) {
this.templatesMu(theme);
}
},
methods: {
...mapMutations([
'templatesMu'
]),
_getLess(filepath, filename) {
console.log(this.templates)
return require("./../static/template/" + this.templates + "/" + filepath + "/"