Vue 换肤的示例实践

2020-06-16 06:06:05易采站长站整理


<img src="../../assets/icon_edit.svg">

这样就导致无法给 icon 动态切换颜色了,所以,我决定改为 font 文件的方式来使用图标。这里推荐一个网站 icomoon ,这个网站可以轻松地将图片转换成 font 文件。图标也非常适合通过 font 的方式来使用,我们可以更加方便的修改图标的大小和颜色。

通过在线转换,我们将下载下来的 font 文件放入项目中,并新建一个 CSS 文件来声明所有图标。


@font-face {
font-family: 'icomoon';
src: url('../assets/fonts/icomoon.eot?vpkwno');
src: url('../assets/fonts/icomoon.eot?vpkwno#iefix') format('embedded-opentype'),
url('../assets/fonts/icomoon.ttf?vpkwno') format('truetype'),
url('../assets/fonts/icomoon.woff?vpkwno') format('woff'),
url('../assets/fonts/icomoon.svg?vpkwno#icomoon') format('svg');
font-weight: normal;
font-style: normal;
}

[class^="icon-"], [class*=" icon-"] {
/* use !important to prevent issues with browser extensions that change fonts */
font-family: 'icomoon' !important;
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
vertical-align: sub;

/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

.icon-edit:before {
content: "e900";
}

之后就能通过 CSS 类名的方式来引用图标了。


<span class="icon-edit"></span>

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


.icon_edit:before {
background-image: linear-gradient(-135deg, #879FFF 0%, #B7A3FF 100%);
}

图片切换

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


<img :src="userImg%20||%20placeholderWoman">

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)