ThemePicker 换肤组件中代码添加
重点:要有效果自己写的颜色必须使用 element-ui 的主题色 #409EFF 才有动态换肤效果
theme: {
immediate: true,
async handler(val, old) {
const oldVal = old || ORIGINAL_THEME
if (typeof val !== 'string') return
const themeCluster = this.getThemeCluster(val.replace('#', ''))
const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
const $message = this.$message({
message: ' Compiling the theme',
customClass: 'theme-message',
type: 'success',
duration: 0,
iconClass: 'el-icon-loading'
})
const getHandler = (variable, id) => {
return () => {
const originalCluster = this.getThemeCluster(
ORIGINAL_THEME.replace('#', '')
)
const newStyle = this.updateStyle(
this[variable],
originalCluster,
themeCluster
)
let styleTag = document.getElementById(id)
if (!styleTag) {
styleTag = document.createElement('style')
styleTag.setAttribute('id', id)
document.head.appendChild(styleTag)
}
styleTag.innerText = newStyle
}
}
if (!this.chalk) {
const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`
await this.getCSSString(url, 'chalk')
}
const chalkHandler = getHandler('chalk', 'chalk-style')
chalkHandler()
let styles = []
if (!this.flag) {
this.flag = true
;[].slice
.call(document.querySelectorAll('link'))
.forEach(async item => {
if (item.rel === 'stylesheet' || item.as === 'style') {
const { data } = await axios.get(item.href)
if (
new RegExp(oldVal, 'i').test(data) &&
!/Chalk Variables/.test(data)
) {
item.remove()
const style = document.createElement('style')
style.innerText = data
style.isAdd = true
styles.push(style)
this.stylesRender(styles, originalCluster, themeCluster)
}
}
})
}
styles = [].slice
.call(document.querySelectorAll('style'))
.filter(style => {
const text = style.innerText
return (
new RegExp(oldVal, 'i').test(text) &&
!/Chalk Variables/.test(text)
)
})
this.stylesRender(styles, originalCluster, themeCluster)
this.$emit('change', val)
$message.close()
}
}
stylesRender(styles, originalCluster, themeCluster) {
styles.forEach(style => {
const { innerText } = style
if (typeof innerText !== 'string') return
style.innerText = this.updateStyle(
innerText,
originalCluster,
themeCluster
)
if (style.isAdd) {
style.isAdd = false
document.head.appendChild(style)
}
})
}
仅仅测试过build出来之后的效果, 请自行测试后酌情使用