vue主题换肤(持续更新,欢迎补充)

需求概况

换肤要求侧边栏背景色,所有button,switch,高亮文字颜色等同时改变

项目概况

基于element-ui开发的vue项目,实现换肤主要使用vue样式绑定:style及封装el-button的组件,用户主题色存储在vuex

基本实现原理

想法比较无脑,控制主题颜色在vuex中存储,通过样式绑定以及自定义组件实现样式变更以达到换肤效果

一步步实现
1. 在vuex中先储存主题变量
//  主题池
themeList: [
   {
       backgroundColor: '#4d71ee',
       color: '#fff'
    },
    {
       backgroundColor: '#304156',
       color: '#fff'
    }
],
//  主题
theme: {
    backgroundColor: '#4d71ee',
    color: '#fff'
}

2.导航栏绑定主题配色
//  第一步 在script中导入存储在vuex中的主题变量
computed: {
  theme () {
    return this.$store.state.theme
  }
}
//  第二步 在template中绑定变量
<template>
  <el-menu :router="true"
    class="nav-menu"
    :default-active="active"
    :background-color="theme.backgroundColor"
    :text-color="theme.color"
    :active-text-color="theme.color"
  >
  // 中间编写导航内容(el-submenu及el-menu-item)
  </el-menu>
</template>

3.封装el-button的组件,在全局引入组件

第一步 封装el-button组件

//  第一步 封装el-button组件
<template>
  <el-button
    :size="size"
    :type="type"
    :loading="loading"
    :disabled="disabled"
    :style="{
      'backgroundColor': theme.backgroundColor,
      'borderColor': theme.backgroundColor,
    }"
    @click="handleClick">
    {{label}}
  </el-button>
</template>

<script>
export default {
  name: 'bxButton',
  props: {
    label: {  // 按钮显示文本
      type: String,
      default: 'Button'
    },
    size: {  // 按钮尺寸
      type: String,
      default: 'mini'
    },
    type: {  // 按钮类型
      type: String,
      default: null
    },
    loading: {  // 按钮加载标识
      type: Boolean,
      default: false
    },
    disabled: {  // 按钮是否禁用
      type: Boolean,
      default: false
    },
    perms: {  // 按钮权限标识,外部使用者传入
      type: String,
      default: null
    }
  },
  data() {
    return {
    }
  },
  computed: {
    theme () {
      return this.$store.state.theme
    }
  },
  methods: {
    handleClick: function () {
      // 按钮操作处理函数
      this.$emit('click', {})
    }
  },
  mounted() {
  }
}
</script>

第二步 在main.js中引入全局组件

//  第二步 在`main.js`中引入全局组件
import elButton from '@/components/themeButton'

Vue.component(elButton.name, elButton)

第三步 在页面中使用封装好的bx-button组件
注意:
a.这里是bx-button不是el-button,如需更改可以更改第一步里script标签中的组件名name
b.之前写在el-button中的内容现在需要写在bx-buttonlabel属性中,否则不生效;

//  第三步 在页面中使用封装好的bx-button组件
<bx-button
  class="confirm"
  type="primary"
  @click="handleClick"
  label="确认"
></bx-button>

4. 给el-switch加上主题配色(由于项目中el-switch使用不多,因此没有制作组件,如需制作组件请参考bx-button的制作方式)
//  第一步 在script中导入存储在vuex中的主题变量
computed: {
  theme () {
    return this.$store.state.theme
  }
}
//  第二步 改变配色
<el-switch
  v-model="scope.row.status"
  :active-color="theme.backgroundColor"
  @change="changeSwitch(scope.row)"
></el-switch>

做到这里基本满足了目前版本的换肤需求,后期如果其他换肤需求会持续更新
ps:其实还想做得更人性化一点的换肤,即用户在色彩盘中选择自己喜欢的颜色进行换肤,实现原理基本一致,这里没有使用css实现换肤就是有局限性,通过vuex来存储变量后期的可扩展性更强

各位如有更好的建议欢迎补充~~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容