[Vuejs]-Is it possible to use local storage to save navigation-drawer visibility?

2👍

Yes you can simply use localStorage to achieve this :

Demo :

new Vue({
  el: '#app',
  data: {
    drawer: false
  },
  mounted() {
    const localStorageValue = JSON.parse(localStorage.drawer);
    this.drawer = localStorageValue ? localStorageValue : false;
  },
  methods: {
    setDrawer() {
     this.drawer = !this.drawer
     localStorage.drawer = this.drawer;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click.stop="setDrawer">Menu</button> <!-- replace this with vuetify v-btn component -->
  <div v-if="drawer">Show Me!</div> <!-- replace this with v-navigation-drawer component -->
</div>

1👍

The link you provided has the necessary information, you need to read the drawer state from local storage when component is mounted and save it when the state changes

Call method toggleDrawer() in you @click handler instead of drawer = !drawer like this @click.stop="toggleDrawer()" or use a watcher on the drawer variable and update the localStorage when it’s changed.

const app = new Vue({
  el: '#app',
  data: {
    drawer: false
  },
  mounted() {
    // Read value from local storage
    if (localStorage.drawer) {
      this.drawer = JSON.parse(localStorage.drawer);
    }
  },
  methods: {
    toggleDrawer() {
      this.drawer = !this.drawer;
      // Save value in local storage
      localStorage.drawer = this.drawer;
    }
  }
})
👤Andrei

Leave a comment