详解Vue 换肤方案验证

2020-06-13 10:32:12易采站长站整理

xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText);
}
};
xhr.open('GET', url);
xhr.send();
});
}

4.把关键词再换回刚刚生成的相应的颜色值,并在页面上添加 style 标签


methods: {
// 点击切换主题
changeTheme(index) {
this.active = index;
this.setNewStyle(this.themeStyleStr, this.colors[index]);
},
// 根据选择的主题颜色,把关键词换成相应的主题颜色,并在页面上添加 style 标签
setNewStyle(originalStyle, colors) {
let oldEl = document.getElementById('theme-style');
let cssText = originalStyle;
Object.keys(colors).forEach(key => {
cssText = cssText.replace(new RegExp(key, 'ig'), colors[key]);
});
const style = document.createElement('style');
style.innerHTML = cssText;
style.id = 'theme-style';
oldEl ? document.head.replaceChild(style, oldEl) : document.head.appendChild(style);
}
}

图片图标切换

1.图片切换和图标切换是同样的原理。在之前新建好的 theme.scss 文件追加图标引入的样式。


.theme-test-icon {
background: url("/static/images/common/list-modify-icon.svg");
}

2.在之前新建好的 theme-colors.js 文件追加图标路径


/*图片统一使用一个路径,更换主题时需要在images文件夹下新建主题文件夹,与原始路径对应,图片文件名须一致
应避免 primaryBtn 与 primaryBtnHover 同时出现,因为正则匹配 primaryBtn 会把 primaryBtnHover 部分匹配出来,达不到效果*/
const colors = [
{
themeId: 0,
primaryBtn: '#409eff', // 主要按钮的背景色
priBtnHover: '#66b1ff', // 主要按钮的悬浮、聚焦背景色
imagePath: '/static/images', // 图片绝对路径
},
{
themeId: 1,
primaryBtn: '#67c23a',
priBtnHover: '#85ce61',
imagePath: '/static/images/theme1',
},
{
themeId: 2,
primaryBtn: '#e6a23c',
priBtnHover: '#ebb563',
imagePath: '/static/images/theme2',
},
];
export default colors;

3.引入需要主题切换的图片/图标,存放于 /static/images/ 之下,每个额外的主题图片需要一个文件夹进行存放,例如 /theme1 或者 /theme2。注意:各个主题的图片文件名要保持不变;图片路径是根据 theme.scss 里面引入图片样式的路径来决定的,可以根据项目实际情况进行调整。

以上,就是Vue项目实现换肤功能的一种方案。换肤功能的实现还有其他方法,欢迎一起交流学习。