Vue 换肤实践
CSS 切换
参考 ElementUi 的方案
1.在 staic 目录下,新建一个 theme.css 文件
2.声明所有可选的主题,每种衍射都对应一个关键词,方便区分
3.通过请求获取 theme.css,将颜色值替换为关键词
4.再将选中的颜色替换上去,加入到head 标签之下(如果之前有,就替换)
图标切换
使用 font 文件的方式使用图片,修改 font 文件来声明所有图标
为了使主题生效,我们也需要把图标的 CSS 写入theme.css文件中
图片切换
项目中还存在很多占位图或者其他图片会随着主题的变化而变化。通过引入所有图片,并用文件名来区分不同主题所对应的图片。在点击切换主题时,切换到主题所对应的文件,就能实现图片切换了。为此,我写了一个 mixin,并在组件中引入 mixin。
placeholderMixin
let callback
const placeholderMixin = {
data () {
return {
placeholderWoman: '',
placeHolderNoReply: '',
placeHolderNothing: ''
}
},
created () {
let themeId = localStorage.getItem('themeId')
let theme = themeId2Name(themeId)
this.setThemeValue(theme)
callback = (theme) => {
this.setThemeValue(theme)
}
bus.$on('changeTheme', callback)
},
destroyed () {
bus.$off('changeTheme', callback)
},
methods: {
setThemeValue (theme) {
this.placeholderWoman = require(`@/assets/placeholder_woman_${theme}.svg`)
this.placeHolderNoReply = require(`@/assets/icon_noreply_${theme}.svg`)
this.placeHolderNothing = require(`@/assets/icon_nothing_${theme}.svg`)
}
}
}
在点击切换主题时,会发射一个changeTheme事件,各组件接收到changeTheme事件,就会为图片重新赋值,也就达到了切换图片的效果。
不过需要所有组件中引入 mixin