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

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

I\'m attempting to watch for localstorage:

Template:

token - {{token}}

Script:

computed: {
  t         


        
6条回答
  •  不思量自难忘°
    2020-12-05 23:40

    Update: vue-persistent-state is no longer maintained. Fork or look else where if it doesn't fit your bill as is.

    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: '

    token - {{token}}

    ' })

    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.

提交回复
热议问题