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

淺唱寂寞╮ 提交于 2019-11-27 03:12:47

问题


I'm attempting to watch for localstorage:

Template:

<p>token - {{token}}</p>

Script:

computed: {
  token() {
    return localStorage.getItem('token');
  }
}

But it doesn't change, when token changes. Only after refreshing the page.

Is there a way to solve this without using Vuex or state management?


回答1:


Sure thing! The best practice in my opinion is to use the getter / setter syntax to wrap the localstorage in.

Here is a working example:

HTML:

<div id="app">
  {{token}}
  <button @click="token++"> + </button>
</div>

JS:

new Vue({
  el: '#app',
  data: function() {
    return {
      get token() {
        return localStorage.getItem('token') || 0;
      },
      set token(value) {
        localStorage.setItem('token', value);
      }
    };
  }
});

And a JSFiddle.




回答2:


If you want to avoid boilerplate (getter/setter-syntax), use vue-persistent-state to get reactive persistent state.

For example:

import persistentState from 'vue-persistent-state';  

const initialState = {
  token: ''  // will get value from localStorage if found there
};
Vue.use(persistentState, initialState);

new Vue({
  template: '<p>token - {{token}}</p>'
})

Now token is available as data in all components and Vue instances. Any changes to this.token will be stored in localStorage, and you can use this.token as you would in a vanilla Vue app.

The plugin is basically watcher and localStorage.set. You can read the code here. It

  1. adds a mixin to make initialState available in all Vue instances, and
  2. watches for changes and stores them.

Disclaimer: I'm the author of vue-persistent-state.




回答3:


The VueJs site has a page about this. https://vuejs.org/v2/cookbook/client-side-storage.html

They provide an example. Given this html template

<template>
  <div id="app">
    My name is <input v-model="name">
  </div>
<template>

They provide this use of the lifecycle mounted method and a watcher.

const app = new Vue({
  el: '#app',
  data: {
    name: ''
  },
  mounted() {
    if (localStorage.name) {
      this.name = localStorage.name;
    }
  },
  watch: {
    name(newName) {
      localStorage.name = newName;
    }
  }
});

The mounted method assures you the name is set from local storage if it already exists, and the watcher allows your component to react whenever the name in local storage is modified. This works fine for when data in local storage is added or changed, but Vue will not react if someone wipes their local storage manually.




回答4:


you can do it in two ways,

  1. by using vue-ls and then adding the listener on storage keys, with

        Vue.ls.on('token', callback)
    

    or

        this.$ls.on('token', callback)
    
  2. by using storage event listener of DOM:

        document.addEventListener('storage', storageListenerMethod);
    


来源:https://stackoverflow.com/questions/42974170/is-there-any-way-to-watch-for-localstorage-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!