main.js:
Vue.prototype.resetSetItem = function (key, newVal) {//实时监听StorageEvent事件
// 创建一个StorageEvent事件
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);
}
使用的页面:
created() {
window.addEventListener("setItem", () => {
let arr=JSON.parse(sessionStorage.getItem("watchStorages"))
console.log(arr,'dataArrs')
})
},
mounted(){
let data = [
{
name: "天弘",
date: "2020-09-30",
type: "货币"
},
{
name: "易方达",
date: "2020-09-30",
type: "货币"
},
{
name: "南方",
date: "2020-09-30",
type: "货币"
},
{
name: "博时",
date: "2020-09-30",
type: "货币"
},
{
name: "嘉实",
date: "2020-09-30",
type: "货币"
},
{
name: "建信",
date: "2020-09-30",
type: "货币"
}
];
this.resetSetItem("watchStorages", JSON.stringify(data));
}