vue3监听localStorage

1.utils中创建方法

export const  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)
    }
}
 

2.在main中引入

import {dispatchEventStroage} from '@/utils/watchLocalStorage.ts'
  app.use(ant);
  app.use(dispatchEventStroage);
  app.mount('#app');

3.在使用的页面调用

const curr: any = ref(localStorage.getItem('curr'))
onMounted(() => {
  window.addEventListener('setItemEvent', function (e) {
    if (e.key === 'curr') {
      curr.value = e.newValue || localStorage.getItem('curr')
    }
  })

})

你可能感兴趣的:(vue,javascript,前端,开发语言)