换肤方案二:|换肤方案二: vue2.0官方实现

演示地址: https://elementui.github.io/theme-chalk-preview/#/zh-CN
原理: element ui 2.0版本之后是基于scss实现的,所有到颜色都是通过变量进行定义,所以我们可以通过修改变量来达到动态换肤的目的.
代码: 1.换肤组件: ThemePicker

.theme-message, .theme-picker-dropdown { z-index: 99999 !important; }.theme-picker .el-color-picker__trigger { height: 26px !important; width: 26px !important; padding: 2px; }.theme-picker-dropdown .el-color-dropdown__link-btn { display: none; }

该组件将选择到颜色保存到vuex的state中, 代码: "this.$store.state.settings.theme"
2.添加store/modules/setting.js文件
import variables from '@/styles/element-variables.scss'const state = { theme: variables.theme }const mutations = { CHANGE_SETTING: (state, { key, value }) => { if (state.hasOwnProperty(key)) { state[key] = value } } }const actions = { changeSetting({ commit }, data) { commit('CHANGE_SETTING', data) } }export default { namespaced: true, state, mutations, actions }

setting.js中默认主题是引入的'@/styles/element-variables.scss'
3. 添加element-variables.scss
/** * I think element-ui's default theme color is too light for long-term use. * So I modified the default color and you can modify it to your liking. **//* theme color */ $--color-primary: #1890ff; $--color-success: #13ce66; $--color-warning: #FFBA00; $--color-danger: #ff4949; // $--color-info: #1E1E1E; $--button-font-weight: 400; // $--color-text-regular: #1f2d3d; $--border-color-light: #dfe4ed; $--border-color-lighter: #e6ebf5; $--table-border:1px solid#dfe6ec; /* icon font path, required */ $--font-path: '~element-ui/lib/theme-chalk/fonts'; @import "~element-ui/packages/theme-chalk/src/index"; // the :export directive is the magic sauce for webpack // https://www.bluematador.com/blog/how-to-share-variables-between-js-and-sass :export { theme: $--color-primary; }

element-variables.scss 文件通过:export将theme导出,这样就能像使用js变量一样使用scss变量了,
准备工作就绪,开始测试
4.添加测试代码
import ThemePicker from '@/components/ThemePicker' export default { name: 'App', components: { ThemePicker }, data() { return { msg: 'Dynamic Themes', theme: 'default', } }, methods: { themeChange(val) { this.$store.dispatch('settings/changeSetting', { key: 'theme', value: val }) } } }

大功告成!
【换肤方案二:|换肤方案二: vue2.0官方实现】优点: 可以动态改变主色调
缺点: 没有足够的个性化,仅仅能修改一些基本的配色

    推荐阅读