持久化存储实时读取
# 重写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
# 全局变量代理
做一个全局变量代理,在页面初始化的时候读取localStorage中的内容
这里全局变量举例 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
# 举例
在vuex vue store中持久存取应用主题theme:dark
这个属性值
state: {
theme: window.localStorage.getItem('theme') || 'default'
},
mutations: {
SET_THEME: (state, value) => {
state.theme = value
window.localStorage.setItem('theme', value)
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
上次更新: 2022/06/05, 20:31:36