Home > Back-end >  Is it possible to use local storage to save navigation-drawer visibility?
Is it possible to use local storage to save navigation-drawer visibility?

Time:04-15

I have a navigation-drawer

<v-navigation-drawer ...content... </v-navigation-drawer>

And a menu button, which hides/shows the navigation drawer.

<v-btn @click.stop="drawer = !drawer"> Menu </v-btn>

If I refresh / change page, I need to click the button to show/hide the navigation-drawer again. Is it possible to use local storage ...

https://v2.vuejs.org/v2/cookbook/client-side-storage.html

...to 'save' whether the navigation-drawer is hidden/visble?

I have checked the documentation / googled, but can not find out how to do this.

CodePudding user response:

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>

CodePudding user response:

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;
    }
  }
})
  • Related