IT이야기

nuxt 라우터 모듈의 router.js 파일에서 Vuex 저장소에 액세스하는 방법?

cyworld 2022. 4. 1. 21:13
반응형

nuxt 라우터 모듈의 router.js 파일에서 Vuex 저장소에 액세스하는 방법?

  • 나는 사용하고 있다
  • 이 작업을 수행하려면router.js전역 라우팅 구성을 추가할 수 있는 파일
  • 그 파일에서 스토어에 액세스하려면 어떻게 해야 하는가?

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모듈은 a를 추가하기로 되어 있었다.beforeEach라우터 후크 대신 Nuxt 플러그인을 통해 실제로 다음을 수행할 수 있음:

// 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'
  ]
}

참조URL: https://stackoverflow.com/questions/64264843/how-to-access-vuex-store-from-nuxt-router-modules-router-js-file

반응형