创建自定义事件retSetItem
Vue.prototype.resSetItem = (key, newVal) => {
if (key === 'playFlagState') {
//监听本地存储 key为 playFlagState时 创建新的监听事件
var newStorageEvent = document.createEvent('StorageEvent')
const storage = {
setItem: function (k, val) {
//执行会话存储
sessionStorage.setItem(k, val)
newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null)
window.dispatchEvent(newStorageEvent)
}
}
return storage.setItem(key, newVal)
}
}
事件调用
this.resSetItem("playFlagState", this.palyFlagState);
事件监听触发
window.addEventListener('setItem', () => {
console.log('playFlagState',sessionStorage.getItem('playFlagState'))
// ...do ...
})