关键词: 一键换肤 Vue

Vue 换肤实践

CSS 切换

参考 ElementUi 的方案
1.在 staic 目录下,新建一个 theme.css 文件
2.声明所有可选的主题,每种衍射都对应一个关键词,方便区分
3.通过请求获取 theme.css,将颜色值替换为关键词
4.再将选中的颜色替换上去,加入到head 标签之下(如果之前有,就替换)

图标切换

使用 font 文件的方式使用图片,修改 font 文件来声明所有图标

为了使主题生效,我们也需要把图标的 CSS 写入theme.css文件中

图片切换

项目中还存在很多占位图或者其他图片会随着主题的变化而变化。通过引入所有图片,并用文件名来区分不同主题所对应的图片。在点击切换主题时,切换到主题所对应的文件,就能实现图片切换了。为此,我写了一个 mixin,并在组件中引入 mixin。

placeholderMixin

  1. let callback
  2. const placeholderMixin = {
  3. data () {
  4. return {
  5. placeholderWoman: '',
  6. placeHolderNoReply: '',
  7. placeHolderNothing: ''
  8. }
  9. },
  10. created () {
  11. let themeId = localStorage.getItem('themeId')
  12. let theme = themeId2Name(themeId)
  13. this.setThemeValue(theme)
  14. callback = (theme) => {
  15. this.setThemeValue(theme)
  16. }
  17. bus.$on('changeTheme', callback)
  18. },
  19. destroyed () {
  20. bus.$off('changeTheme', callback)
  21. },
  22. methods: {
  23. setThemeValue (theme) {
  24. this.placeholderWoman = require(`@/assets/placeholder_woman_${theme}.svg`)
  25. this.placeHolderNoReply = require(`@/assets/icon_noreply_${theme}.svg`)
  26. this.placeHolderNothing = require(`@/assets/icon_nothing_${theme}.svg`)
  27. }
  28. }
  29. }

在点击切换主题时,会发射一个changeTheme事件,各组件接收到changeTheme事件,就会为图片重新赋值,也就达到了切换图片的效果。

不过需要所有组件中引入 mixin