Home > database >  How to watch localstorage in Vue.js 2
How to watch localstorage in Vue.js 2

Time:10-17

How do I know about changes in Banana.vue?

I using, addEventListener, @watch... But, not working........................

index.vue is import Apple.vue, Banana.vue

in Apple.vue
localStorage.setItem('fruit', 'apple)

in Banana.vue

@watch(localStorage.getItem('fruit' || '')
    changeFruit() {
    this.fruit = localStorage.getItem('fruit')
}

CodePudding user response:

use getter and setter

data() {
    return {
      get token() {
        return localStorage.getItem('token') || 0;
      },
      set token(value) {
        localStorage.setItem('token', value);
        this.fruit = localStorage.getItem('fruit')

      }
    };
  }

CodePudding user response:

LocalStorage is not reactive but you can access the localStorage value in the component like this :

Vue.component('apple', {
  props: ['childmsg'],
  template: '<p>{{ childmsg }}</p>',
  mounted() {
    localStorage.setItem('fruit', 'apple');
  }
});

Vue.component('banana', {
  data: {
    fruit: ''
  },
  props: ['childmsg'],
  template: '<p>{{ childmsg }}</p>',
  mounted() {
    if (localStorage.fruit) {
      this.fruit = localStorage.fruit;
      console.log(this.fruit);
    }
  }
});

var app = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <apple childmsg="This is Apple"></apple>
  <banana childmsg="This is Banana"></banana>
</div>

  • Related