PirateApp
PirateApp

Reputation: 6220

How to access Vuex store from nuxt router module's router.js file?

Upvotes: 2

Views: 2884

Answers (1)

tony19
tony19

Reputation: 138466

You could access the store through the root context, which Nuxt provides in window.$nuxt outside Vue components:

// router.js
import Router from 'vue-router'

export function createRouter(ssrContext, createDefaultRouter, routerOptions) {
  const options = routerOptions ? routerOptions : createDefaultRouter(ssrContext).options

  const router = new Router({
    ...options
  })

  if (process.client) {
    router.beforeEach((to, from, next) => {
      // Since `beforeEach` is invoked before `window.$nuxt` is
      // initialized, use `setTimeout` without a timeout to wait
      // until the next macro tick.
      setTimeout(() => {
        window.$nuxt.$store.dispatch('myAction')
      })

      next()
    })
  }

  return router
}

If the only reason for using @nuxtjs/router module were to add a beforeEach router hook, you could actually accomplish that with a Nuxt plugin instead:

// plugins/router.js
export default ({ app, store }) => {
  app.router.beforeEach((to, from, next) => {
    store.dispatch('myAction')
    next()
  })
}

// nuxt.config.js
export default {
  plugins: [
    '~plugins/router.js'
  ]
}

Upvotes: 6

Related Questions