vue element 多套主题换肤

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37068028/article/details/85229682

1. 生成element皮肤

1.1 下载custom-element-theme

git clone https://github.com/PanJiaChen/custom-element-theme.git

1.2 安装

npm i element-theme -g

1.3 修改element-variables.scss主颜色

$--color-primary: #f81c1c !default;

1.4 在项目 custom-element-theme 下生成皮肤,执行

et

2 将生成的element主题,移入到项目中

在这里插入图片描述

3. 切换主题

3.1 切换主题组件

在这里插入图片描述

// skin.vue
<el-dropdown-menu slot="dropdown">
  <el-dropdown-item
    v-for="(item,index) in skins"
    :key="index"
    :command="item.name">
    <div :class="'skin skin-' + item.name"></div>
  </el-dropdown-item>
</el-dropdown-menu>
...

skins: [
    { name: '96b327' },
    { name: '083886' }
  ]
...

global.changeTheme(command)

3.2 引入主题文件

// global.js
import themeArray from './themeArray'

export const global = {
  // 换肤添加class函数
  toggleClass(element, className) {
    if (!element || !className) {
      return
    }
    element.className = className
  },
  // 切换主题函数
  changeTheme(themeValue) {
    // 需要移到单独的文件存放
    const cssArray = themeArray
    for (let i = 0, len = cssArray.length; i < len; i++) {
      const itemPath = './' + themeValue.toLowerCase() + '/' + cssArray[i].toLowerCase() + '.css'
      loadCss(itemPath)
    }
    function loadCss(path) {
      const head = document.getElementsByTagName('head')[0]
      const link = document.createElement('link')
      link.href = path
      link.rel = 'stylesheet'
      link.type = 'text/css'
      head.appendChild(link)
    }
  }
}

3.3 引入主题组件文件

// themeArray.js
const themeArray = [
  'Input',
  'input-number',
  'Radio',
  'Checkbox',
  'Switch',
  'Select',
  'Option',
  'Button',
  'button-group',
  'table-column',
  'date-picker',
  'time-select',
  'Loading'
]
export default themeArray

3.4 为body添加命名空间

在这里插入图片描述

// global.js
...
this.toggleClass(document.body, 'custom-' + themeValue)
localStorage.setItem('theme', themeValue)

3.5 默认加载主题

// main.js
if (localStorage.getItem('theme')) {
  global.changeTheme(localStorage.getItem('theme'))
} else {
  global.changeTheme('96b327')
}

4. 编写自定义皮肤样式

在各自的命名空间下,编写自定义样式
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_37068028/article/details/85229682