Is there any way to 'watch' for localstorage in Vuejs?

前端 未结 6 1866
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 23:20

I\'m attempting to watch for localstorage:

Template:

token - {{token}}

Script:

computed: {
  t         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 23:49

    localStorage is not reactive but I needed to "watch" it because my app uses localstorage and didn't want to re-write everything so here's what I did using CustomEvent.

    I would dispatch a CustomEvent whenever you add something to storage

    localStorage.setItem('foo-key', 'data to store')
    
    window.dispatchEvent(new CustomEvent('foo-key-localstorage-changed', {
      detail: {
        storage: localStorage.getItem('foo-key')
      }
    }));
    

    Then where ever you need to watch it do:

    mounted() {
      window.addEventListener('foo-key-localstorage-changed', (event) => {
        this.data = event.detail.storage;
      });
    },
    data() {
      return {
        data: null,
      }
    }
    

提交回复
热议问题