代码之家  ›  专栏  ›  技术社区  ›  PirateApp

如何从nuxt路由器模块的路由器.js文件?

  •  0
  • PirateApp  · 技术社区  · 6 年前
    0 回复  |  直到 6 年前
        1
  •  2
  •   tony19 thanksd    6 年前

    您可以通过根上下文访问存储,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'
      ]
    }
    
    推荐文章