换肤功能的实现以及监听storage实现多个标签页一起换肤

时间:2020-12-12 21:16:53

1:需求:项目的侧边栏实现换肤功能,核心代码:

updateSkin (val) {
const existSkinLink = document.head.querySelector('link[id="sidebar"]')
if (existSkinLink) {
existSkinLink.setAttribute('href', `//static.zhaopin.com/newcrm/static/skin/${val}02.css`)
} else {
const skinLink = document.createElement('link')
skinLink.setAttribute('id', 'sidebar')
skinLink.setAttribute('href', `//static.zhaopin.com/newcrm/static/skin/${val}02.css`)
skinLink.setAttribute('rel', `stylesheet`)
document.head.appendChild(skinLink)
}
}

注意 此处必须引用css 不能是styl sass less 等

2:需求:打个多个标签页后,A标签换肤后,B标签不会自动换肤,要刷新才行

实现思路:监听storage

核心代码:

1:在mounted钩子里增加监听,在destroyed钩子里销毁

mounted () {
window.addEventListener('storage', this.toUpdateSkin)
},
destroyed () {
window.removeEventListener('scroll', this.scrollAction)
window.removeEventListener("storage", this.toUpdateSkin)
},

2:有A、B两个标签页,在A标签页点击切换皮肤的按钮后,走的是方法1changeSkin,在changeSkin里做了些业务操作,可忽略,关键代码localStorage.setItem(${env}${empId}cmpSkin, colorBg) 修改localStorage,然后调用方法3 this.updateSkin(colorBg)实现A标签页换肤

在B标签页监听到localStorage改变之后,自动执行方法2toUpdateSkin经过一些业务代码后调用方法3this.updateSkin(colorBg)实现B标签页换肤

方法1
async changeSkin (colorBg) {
if (this.menuSkinColor === colorBg) {
return
}
const key = 'colorBg'
const url = this.api.myCustomer.saveSettings
const type = 1
const params = {
column: 'emp_query_json',
type,
json: {
[key]: colorBg,
}
}
try {
this.$http.post(url, params)
const empId = Common.getCookie('ZPSSO_USER_EMPID')
const env = process.env.NODE_ENV
localStorage.setItem(`${env}${empId}cmpSkin`, colorBg)
this.setLeftLoading(true)
this.menuSkinColor = colorBg
await this.getLeftMenuData()
this.$nextTick(() => {
setTimeout(() => {
this.setLeftLoading(false)
this.updateSkin(colorBg)
}, 0)
})
} catch (e) {
this.common.handleError(e, this)
}
},
方法2
async toUpdateSkin (e) {
const empId = Common.getCookie('ZPSSO_USER_EMPID')
const env = process.env.NODE_ENV
if (e && e.key === `${env}${empId}cmpSkin`) {
const arr = ['blackBg', 'grayBg']
let color = ''
if (arr.includes(e.newValue) && arr.includes(e.oldValue) && e.oldValue !== e.newValue) {
color = e.newValue
} else {
color = 'blackBg'
}
this.setLeftLoading(true)
this.menuSkinColor = color
await this.getLeftMenuData()
this.$nextTick(() => {
setTimeout(() => {
this.setLeftLoading(false)
this.updateSkin(color)
}, 0)
})
}
},
方法3
updateSkin (val) {
const existSkinLink = document.head.querySelector('link[id="sidebar"]')
if (existSkinLink) {
existSkinLink.setAttribute('href', `//static.zhaopin.com/newcrm/static/skin/${val}02.css`)
} else {
const skinLink = document.createElement('link')
skinLink.setAttribute('id', 'sidebar')
skinLink.setAttribute('href', `//static.zhaopin.com/newcrm/static/skin/${val}02.css`)
skinLink.setAttribute('rel', `stylesheet`)
document.head.appendChild(skinLink)
}
},