vue如何監(jiān)聽頁面緩存事件
監(jiān)聽頁面緩存事件
事情的起因是這樣的
項目中需要用到websocket,在網(wǎng)頁剛打開的時候,就要進行對話的連接綁定,就我這菜鳥來說,第一次這么搞事情,也是剛接觸websocket沒多久,這咋整???在App.vue中設(shè)置了綁定,所有的信息返回都在app.vue組件里面,但是其他組件怎么去獲取?而且需要緩存到本地。而當(dāng)初我還沒接觸vuex,所以在其他組件里面獲取服務(wù)器返回的信息只能借助于localStorage,這就郁悶了,這緩存咋監(jiān)聽呀?
首先在main.js里面配置vue原型:
Vue.prototype.resetSetItem = (key, newVal) => {
? if (key === 'websocketHistory') {
? ? // 創(chuàng)建一個StorageEvent事件
? ? let newStorageEvent = document.createEvent('StorageEvent');
? ? const storage = {
? ? ? setItem: (k, val) => {
? ? ? ? localStorage.setItem(k, val);
? ? ? ? // 初始化創(chuàng)建的事件
? ? ? ? newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
? ? ? ? // 派發(fā)對象
? ? ? ? window.dispatchEvent(newStorageEvent);
? ? ? }
? ? };
? ? return storage.setItem(key, newVal);
? }
};這個時候,在其他頁面寫入緩存就不能直接用localStorage了
你需要這么設(shè)置
this.resetSetItem('websocketHistory', data);然后在需要監(jiān)聽的頁面中,created函數(shù)中使用
window.addEventListener('setItem', () => {
? console.log(JSON.parse(localStorage.getItem('websocketHistory'))); ? ??
});如此,便能在app.vue組件中使用獲取服務(wù)器返回的信息并存入緩存,在其他組件,比如回話列表頁面就可以實時更新列表,包括對話頁面。
監(jiān)聽緩存事件代碼
隨著H5的更新,前端經(jīng)常使用本地存儲進行交互處理數(shù)據(jù),如果想要監(jiān)聽緩存的變化,以下代碼就是您想要的。
在main創(chuàng)建緩存事件
// 監(jiān)聽緩存事件
Vue.prototype.$addStorageEvent = function(type, key, data) {
if (type === 1) {
// 創(chuàng)建一個StorageEvent事件
var newStorageEvent = document.createEvent("StorageEvent");
const storage = {
setItem: function(k, val) {
localStorage.setItem(k, val);
// 初始化創(chuàng)建的事件
newStorageEvent.initStorageEvent(
"storageItem",
false,
false,
k,
null,
val,
null,
null
);
// 派發(fā)對象
window.dispatchEvent(newStorageEvent);
},
};
return storage.setItem(key, data);
} else {
// 創(chuàng)建一個StorageEvent事件
var newStorageEvent = document.createEvent("StorageEvent");
const storage = {
setItem: function(k, val) {
sessionStorage.setItem(k, val);
// 初始化創(chuàng)建的事件
newStorageEvent.initStorageEvent(
"setItem",
false,
false,
k,
null,
val,
null,
null
);
// 派發(fā)對象
window.dispatchEvent(newStorageEvent);
},
};
return storage.setItem(key, data);
}
};在組件生命周期中
監(jiān)聽緩存事件并取值
? ? window.addEventListener(
? ? ? "stotageItem",
? ? ? (e) => { // e代表存儲的數(shù)據(jù) { a:1 }
? ? ? ? JSON.parse(e.a)
? ? ? },
? ? ? false
? ? );在組件業(yè)務(wù)代碼
進行緩存使用
?this.$addStorageEvent(0, "useStorage",?
? ? // 寫入數(shù)據(jù)
? ? JSON.stringify({ a:1 })
?);以上就是全部代。僅為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue 路由視圖 router-view嵌套跳轉(zhuǎn)的實現(xiàn)
這篇文章主要介紹了vue 路由視圖 router-view嵌套跳轉(zhuǎn),主要實現(xiàn)的內(nèi)容有制作一個登錄頁面,跳轉(zhuǎn)到首頁,首頁包含菜單欄、頂部導(dǎo)航欄、主體,標(biāo)準(zhǔn)的后臺網(wǎng)頁格式,菜單點擊顯示不同的頁面,感興趣的小伙伴請參考下面文章內(nèi)容2021-09-09
vue使用Google Recaptcha驗證的實現(xiàn)示例
我們最近的項目中需要使用谷歌機器人驗證,所以就動手實現(xiàn)一下,本文就來詳細的介紹一下vue Google Recaptcha驗證,感興趣的可以了解一下2021-08-08

