Search code examples
vuejs3getterpinia

Access current route inside a getter in Pinia?


I would like to know what is the current route so that I can compute the size of the sidebar.

import { defineStore } from 'pinia'

export const useSidebarStore = defineStore('sidebar', {
  state: () => {
    return {
      full: true // can be toggled by clicking on the sidebar toggle button
    }
  },
  getters: {
    // TODO secondarySidebar is open if current route is settings
    // secondarySidebarOpen: (state) =>
    // TODO create a getter that returns the current route
    currentRoute (state, getters, rootState, rootGetters) {
      return 
    }
  },
  actions: {
  }
})

export default useSidebarStore

Can you please help?


Solution

  • A solution I found is to store the current route to the state of the store by using beforeEach method of the router.

    import { createRouter, createWebHistory } from 'vue-router'
    import routes from '@/router/routes.js'
    import { useSidebarStore } from '@/stores/sidebar.js'
    
    const router = createRouter({
      history: createWebHistory(import.meta.env.BASE_URL),
      routes
    })
    
    router.beforeEach(async (to) => {
      const sidebarStore = useSidebarStore()
      sidebarStore.currentRoutePath = to.path
      return true
    })
    export default router