持久化数据
更良好的读取持久化数据
# 全局变量代理
做一个全局变量代理 放在运存中
这里全局变量举例 window._theme
读
const getTheme = () => { return window._theme || window.localStorage.getItem('theme') || 'default' }
1
2
3写
const setTheme = (value) => { window.localStorage.setItem('theme': value) return window._theme = value }
1
2
3
4
# 监听localStorage变化
# 重写localStorage
var orignalSetItem = localStorage.setItem;
localStorage.setItem = function(key,newValue){
var setItemEvent = new Event("setItemEvent");
setItemEvent.newValue = newValue;
window.dispatchEvent(setItemEvent);
orignalSetItem.apply(this,arguments);
}
window.addEventListener("setItemEvent", function (e) {
alert(e.newValue);
});
localStorage.setItem("name","wang");
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
上次更新: 2022/06/05, 20:31:36