Vue Ant Design Pro 中定制主题

Vue Ant Design Pro 中定制主题

  • 需求
  • 定制主题
  • 去除“正在切换主题”过渡效果

 

需求

  • 项目要求使用草绿色的主题色
  • 并且去除如下的loading效果

    定制主题

    • 这里可以参照 Ant Design Pro of Vue 官方文档哦
    • 定制方式是使用 less 的 modifyVars 的方式进行覆盖变量
    • 官方文档已经给出了 webpack 、vue cli 2 以及 vue cli 3 三种不同场景下主题的定制方式。这里不再过多赘述
      • vue cli 3 下定制主题方式如下:
        • 项目根目录下修改文件 vue.config.js
        • module.exports = {css: {loaderOptions: {less: {lessOptions: {modifyVars: {'primary-color': '#1DA57A','link-color': '#1DA57A','border-radius-base': '2px',},javascriptEnabled: true,},},},},
          };

去除“正在切换主题”过渡效果

  • Ant Design Pro of Vue 中提供了一个可以在线切换主题和布局的设置抽屉,使用这个抽屉可以很方便的查看更换主题的效果,无需重启脚手架。
  • 真实项目中是需要去掉这个在线主题的定制抽屉的
  • 另一个问题是每次刷新页面是都会出现“正在切换主题”的全局提示
  • 如何去除“正在切换主题”的全局提示呢?
  • 方法很简单:
    • 首先我们需要按照上一节的方法定制好自己的主题哦,不然的话,去除全局提示后主题就还是 ant design 的默认主题哦
    • 上一步之后,就需要打开文件 src/layouts/BasicLayout.vue,大概在137~139行,可以看到这样一段代码:
      if (process.env.NODE_ENV !== 'production' || process.env.VUE_APP_PREVIEW === 'true') {updateTheme(this.settings.primaryColor)
      }
      
      • 注释或删除掉这段代码就可以啦
  • 我们来看看上节中 updateTheme 方法的源码
import client from 'webpack-theme-color-replacer/client'
import generate from '@ant-design/colors/lib/generate'
import { message } from 'ant-design-vue'export const themeColor = {getAntdSerials (color) {// 淡化(即less的tint)const lightens = new Array(9).fill().map((t, i) => {return client.varyColor.lighten(color, i / 10)})// colorPalette 变换得到颜色值const colorPalettes = generate(color)const rgb = client.varyColor.toNum3(color.replace('#', '')).join(',')return lightens.concat(colorPalettes).concat(rgb)},changeColor (newColor) {const options = {newColors: this.getAntdSerials(newColor), // new colors array, one-to-one corresponde with `matchColors`changeUrl (cssUrl) {return `/${cssUrl}` // while router is not `hash` mode, it needs absolute path}}return client.changer.changeColor(options, Promise)}
}export const updateTheme = newPrimaryColor => {const hideMessage = message.loading('正在切换主题', 0)themeColor.changeColor(newPrimaryColor).then(r => {hideMessage()})
}export const updateColorWeak = colorWeak => {// document.body.className = colorWeak ? 'colorWeak' : '';const app = document.body.querySelector('#app')colorWeak ? app.classList.add('colorWeak') : app.classList.remove('colorWeak')
}
  • 很明显,出现“正在切换主题”全局提示的罪魁祸首就是 updateTheme 方法里面的 hideMessage 方法
  • 其实之前想到的另一个方法就是直接使用 themeColor 的 changeColor 方法,而不是使用 updateTheme
  • 但不幸的是,这里虽然 export 了 themeColor,但 pro-layout 的 index.js 里面却没有 export 出去,所以项目中我们也就无从用起了 ε=(´ο`*)))唉
  •  

posted @ 2023-05-18 20:52  wangyb56  阅读(322)  评论(0编辑  收藏  举报