How to access store inside Router.beforeEach?



  • I’m doing this, to check auth state

    export default function (router, store, Vue /* { store, ssrContext } */) {
        const Router = new VueRouter({
            scrollBehavior: () => ({ x: 0, y: 0 }),
            routes,
    
            // Leave these as is and change from quasar.conf.js instead!
            // quasar.conf.js -> build -> vueRouterMode
            // quasar.conf.js -> build -> publicPath
            mode: process.env.VUE_ROUTER_MODE,
            base: process.env.VUE_ROUTER_BASE
        })
    
        Router.beforeEach((to, from, next) => {
            console.log('beforeEach from', from, 'to', to)
            console.log(store.getters.auth.isLoggedIn)
    
            // if (to.matched.some(record => record.meta.requiresAuth)) {
            // }
    
            next()
        })
    
        return Router
    }
    

    The problem is that inside beforeEach callback, store is undefined.

    How to workaround this?



  • Try with :

    export default function ({store}) {
      const Router = new VueRouter({
        // ...
      }
    Router.beforeEach((to, from, next) => {
      console.log(store.getters.auth.isLoggedIn)
      // ...
      next()
     }
     return Router
    }
    

    You can also make a boot file and declare your beforeEach hook there, as documented here : https://quasar.dev/quasar-cli/cli-documentation/boot-files#Router-authentication



  • @realtebo btw, most of your recent questions are in the docs, please do read it. Use the search function in there for convenience.


Log in to reply