[Vuejs]-Vue router – beforeEach, detect click on same path

1👍

I had a similar issue and here’s my 2 cents.

From a UX stand, it’s not a good solution to toggle the sidebar “on sidebar link/item click”.

Even if the sidebar is open, and you close it by clicking on the link that’s points on the current path, how would you open the sidebar again?

As from my situation, I put the same logic in my router.js:

router.beforeEach((to, from, next) => {
  store.commit('toggleSidebar', true)
  //other logic
})

And in my Sidebar.vue component I only have the computed method to fetch the current value toggleSidebar:

<template>
  <aside :class="{close: getSidebar}">
    <!-- other markup -->
  </aside>
</template>

...

computed: {
  getSidebar() {
    return this.$store.state.isSidebarClosed
  }
}

And now, to toggle the sidebar I have a Navigation.vue components (header) that has a button to do it:

<button type="button" @click="toggleSidebar">
   <span v-if="sidebarStatus" class="hamburger-icon"></span>
   <span v-else class="close-icon"></span>
</button>

...

methods: {
  toggleSidebar() {
    this.$store.commit('toggleSidebar', !this.$store.state.isSidebarClosed)
  }
},
computed: {
  sidebarStatus() {
    return this.$store.state.isSidebarClosed
  }
}

Hope it helps.

👤Vucko

Leave a comment