vue 换肤

/* eslint-disable */
// 设置文件
import setting from "@/setting.js";

const themeList = setting.theme.list;

export default {
  namespaced: true,
  state: {
    // 主题
    list: themeList,
    // 现在激活的主题 这应该是一个名字 不是对象
    activeNumber: 0,
    activeName: setting.theme.list[0].name
  },
  actions: {
    /**
     * @description 激活一个主题
     * @param {Object} state vuex state
     * @param {String} themeValue 需要激活的主题名称
     */
    set({ state, commit, dispatch }, activeNumber) {
      return new Promise(async resolve => {
        // 检查这个主题在主题列表里是否存在
        if (activeNumber < state.list.length) {
          state.activeNumber = activeNumber;
          state.activeName = state.list[activeNumber].name;
        }
        // 将 vuex 中的主题应用到 dom
        commit("dom");
        // 持久化
        await dispatch(
          "cptwebsite/db/set",
          {
            path: "theme.activeName",
            value: state.activeName,
            user: false
          },
          { root: true }
        );
        // end
        resolve();
      });
    },
    /**
     * @description 从持久化数据加载主题设置
     * @param {Object} state vuex state
     */
    load({ state, commit, dispatch }) {
      return new Promise(async resolve => {
        // store 赋值
        let activeName = await dispatch(
          "cptwebsite/db/get",
          {
            path: "theme.activeName",
            defaultValue: state.activeName,
            user: false
          },
          { root: true }
        );

        // 检查这个主题在主题列表里是否存在
        const _index = state.list.findIndex(e => e.name === activeName);
        if (_index > -1) {
          state.activeNumber = _index;
          state.activeName = activeName;
        } else {
          // 持久化
          await dispatch(
            "cptwebsite/db/set",
            {
              path: "theme.activeName",
              value: state.activeName,
              user: false
            },
            { root: true }
          );
        }
        // 将 vuex 中的主题应用到 dom
        commit("dom");
        // end
        resolve();
      });
    }
  },
  mutations: {
    /**
     * @description 将 vuex 中的主题应用到 dom
     * @param {Object} state vuex state
     */
    dom(state) {
      document.body.className = `theme-${state.activeName}`;
    }
  }
};

  

import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState('cptwebsite/theme', ['activeName'])
  },
  created () {
    this._getLess()
  },
  methods: {
    _getLess () {
      return require(`@/assets/styles/theme/${this.activeName}/index.less`)
    },
    _getImage (filepath, filename) {
      return require(`@/assets/templates/${this.activeName}/images/${filepath}/${filename}`)
    },
    _getPublicImage (filepath, filename) {
      return require(`@/assets/images/${filepath}/${filename}`)
    }
  },
  watch: {
    activeName () {
      this._getLess()
    }
  }
}

  

你可能感兴趣的:(vue 换肤)