LoginSignup
1
3

More than 3 years have passed since last update.

Vueでローカルストレージをwatchする

Posted at

Vueでローカルストレージのwatchはできない

結論を先に述べると、ローカルストレージはリアクティブでないので、Vueのwatchですることはできない。
この記事では代替案を記載する

代替案:storageのチェンジイベントをaddEventListenerに登録する

    mounted: function() {
        this.ls_event_handle = window.addEventListener('storage', this.eventMethod);
    },
    methods: {
        eventMethod: function(event) {
            let new_val = event.newValue;
            let old_val = event.oldValue;
            switch (event.key) {
                case LOCALSTORAGEKEY1 :
                    console.log(new_val);
                    break;

                case LOCALSTORAGEKEY2 :
                    console.log(old_val);
                    break;

                default:
                    console.log(event.key):
                    break;
                default :
                    break;
            }
        }
    },
    destroyed: function() {
        window.removeEventListener(this.ls_event_handle);
    },

代替案:vue-lsを使用する

※ 未検討であるため、リンクのみ記載

vue-ls

参考

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3