如何从 nuxt 路由器模块的 router.js 文件访问 Vuex 存储?
How to access Vuex store from nuxt router module's router.js file?
- 我正在使用
nuxt-community/router-module
- 它需要您创建一个
router.js
文件,您可以在其中添加全局路由配置
- 如何从该文件访问商店?
您可以通过 Nuxt 在 window.$nuxt
Vue 组件外部提供的根上下文访问商店:
// 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
}
如果使用 @nuxtjs/router
模块的唯一原因是添加一个 beforeEach
路由器挂钩,您实际上可以使用 Nuxt plugin 来实现:
// 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'
]
}
- 我正在使用
nuxt-community/router-module
- 它需要您创建一个
router.js
文件,您可以在其中添加全局路由配置 - 如何从该文件访问商店?
您可以通过 Nuxt 在 window.$nuxt
Vue 组件外部提供的根上下文访问商店:
// 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
}
如果使用 @nuxtjs/router
模块的唯一原因是添加一个 beforeEach
路由器挂钩,您实际上可以使用 Nuxt plugin 来实现:
// 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'
]
}