在项目的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 + "/" + filename + "/index.less");
},
},
})
因为用到了vuex,所以还需要import进来:
import { mapState, mapGetters, mapMutations } from 'vuex'
_getLess方法传入两个用来标识样式文件位置的参数,调用该方法会动态的require一个样式文件。this.theme
为store中存储的当前皮肤的信息,我们在选择皮肤时会将这个信息存储下来。并且我们要将皮肤相关的样式文件存储在_getLess方法对应的文件夹下。
在vuex中加入方法用于存储当前皮肤信息:
export default {
state: {
templates: "2",
},
getters: {
templates(state) {
return state.templates;
}
},
mutations: {
templatesMu(state, val) {
if (val) {
state.templates = val;
}
},
},
actions: {
}
}
created: () {
this._getLess("home","test1");
},
两个标识路径的参数方便程序的扩展。 这样当程序加载这个页面时会首先调用created方法,然后动态加载less样式文件。
// 存储当前皮肤的信息
setTheme(themeFile) {
localStorage.theme = themeFile.data;
this.$store.commit('templatesMu', themeFile.data);
this.show = false;
location.reload();
}
这样就实现了用less语法来完成换皮肤功能。可以看到换皮肤之后调用了location.reload()
方法直接刷新页面,这也是这个换皮肤的方法的最大的不足之处了,如果有更好的思路的话欢迎指正~