vuejs 2 local storage

by Felipe Kautzmann

HTML

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-ls"></script>
<div>
  <a href="https://www.npmjs.com/package/vue-ls">Vue localstorage plugin</a>
  <br>
  <br>
</div>

<div id="app">
  counter: {{counter}}
  <div>
    <button type="button" @click="increment()">Increment</button>
    <button type="button" @click="decrement()">Decrement</button>
  </div>
</div>

JavaScript

Vue.use(VueLocalStorage);

new Vue({
  el: '#app',
  data: function() {
    return {
      counter: 0
    };
  },
  watch: {
    counter: function(val) {
      this.$ls.set('counter', val)
    }
  },
  created: function() {
    this.counter = this.$ls.get('counter', 0);
    var _this = this;
    this.$ls.on('counter', function(val) {
      _this.counter = val;
    });
  },
  methods: {
    increment: function() {
      this.counter++;
    },

    decrement: function() {
      this.counter--;
    }
  }
});