vue监听本地localStorage变化

vue监听本地localStorage变化

tool.js

// 重写setItem事件,当使用setItem的时候,触发,window.dispatchEvent派发事件
function dispatchEventStroage() {
    
    
    const signSetItem = localStorage.setItem
    localStorage.setItem = function(key, val) {
    
    
        let setEvent = new Event('setItemEvent')
        setEvent.key = key
        setEvent.newValue = val
        window.dispatchEvent(setEvent)
        signSetItem.apply(this, arguments)
    }
}

export default dispatchEventStroage;

main.js

import tool from "@/publicStorage/tool.js"; // 改成你的路径
app.use(tool)

需要监听的组件

onMounted(() => {
    
    
  window.addEventListener("setItemEvent", (event) => {
    
    
    if (event.key === "yourkey") {
    
    
      console.log(event.newValue); // yourkey 对应的新值
    }
  });
});

猜你喜欢

转载自blog.csdn.net/weixin_43136717/article/details/127651484