Nuxt, accessing vuex store in router.js (@nuxt/router)

Viewed 848

Using the @nuxt/router module I have a router.js with my routes and I want to do some stuff in router.beforeEach... which is dependent on state values in different store modules.

My store folder looks like this: index.js, auth.js, language.js ...

New to Nuxt, I have trouble understanding how to make the store accessible in this route file. I get errors when I try to import it, do I need to inject the context ? is the context already available ? Change the store set-up and export it ? Use middleware ?

I mananged to get partly there with import {state} from '@/store/language' and then getting a value with state().activeLang but this value doesn't update when the store value changes, and a single import only covers part of the need.

My router.js file looks like this:

import Vue from 'vue'
import Router from 'vue-router'

import Home from '@/views/Home/Home'
import Admin from '@/views/Admin/Admin'

Vue.use(Router)

//do I need to pass the context into this function ???

export function createRouter() {
  const router = new Router({
    mode: 'history',
    routes: [
      { path: '/', component: Home, name: 'home' },
      { path: '/admin', component: Admin, name: 'admin' },
    ]
  })

  router.beforeEach((to, from, next) => {

   // do stuff here...
   // e.g. check auth store if user is authenticated
   // e.g. get active language from language store

    return next();
  });

  return router
}``` 

0 Answers
Related