Vue localStorage sync

Sync vue data between webpages on the same domain

by Christopher O

HTML

<div id="app">
  <h2>Todos ({{ lastUpdate }}):</h2>
  <ol>
    <li v-for="todo in todos">
      <label>
        <input type="checkbox" v-on:change="toggle(todo)" v-bind:checked="todo.done">

        <del v-if="todo.done">
          {{ todo.text }}
        </del>
        <span v-else>
          {{ todo.text }}
        </span>
      </label>
    </li>
  </ol>
  <p>{{display}}
  </p>
  </p>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

Vue

console.clear();

// localStorage is usually limited to 5MB (limited resources on moble)
// See link below showing array -> json -> b64 -> LZ Compress -> localstorage
// https://jsfiddle.net/chrisorso/0dc4nqbh/

// Demo: http://jsfiddle.net/6szpowkm/embedded/result/

/* window.addEventListener('storage', () => {
  // When local storage changes, dump the list to
  // the console.
  //console.log(JSON.parse(window.localStorage.getItem('sampleList')));
  console.log('Event: local storage change 1');
}); */

window.onstorage = () => {
  // When local storage changes, dump the list to
  // the console.
  // console.log(JSON.parse(window.localStorage.getItem('sampleList')));
  console.log('Event: local storage change 2');
};

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true }
    ],
    lastUpdate: 0,
    display: '',
  },
  mounted() {
  	let self = this;
    if(localStorage.todos){
    	self.display = localStorage.todos;
      self.todos = JSON.parse(localStorage.todos) 
     };
    if(localStorage.lastUpdate) self.lastUpdate = localStorage.lastUpdate;
    
    // Polling
    setInterval(function(){
      self.checkStorage();
    }, 300);
    
    // Event listener
    window.addEventListener("storage", self.storageEvent, false);
    
  },
  watch:{
    lastUpdate(newTime) {
      localStorage.lastUpdate = newTime;
    }
  },
  methods: {
  	storageEvent: function(event){
    	let self = this;
      if(!event) { event = window.event; } // ie suq
      if(!event.newValue) return;          // do nothing if no value to work with
      if (event.key == 'getSessionStorage') {
      	console.log('Event: getSessionStorage');
        // another tab asked for the sessionStorage -> send it
        //localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
        // the...