- I am using
nuxt-community/router-module - It requires you to create a
router.jsfile where you can add global routing configuration - How do I access the store from that file?
nuxt-community/router-modulerouter.js file where you can add global routing configurationYou 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'
]
}