【问题标题】:How to access Vuex store from nuxt router module's router.js file?如何从 nuxt 路由器模块的 router.js 文件访问 Vuex 商店?
【发布时间】:2021-01-23 15:18:27
【问题描述】:
  • 我正在使用nuxt-community/router-module
  • 它需要您创建一个router.js 文件,您可以在其中添加全局路由配置
  • 如何从该文件访问商店?

【问题讨论】:

  • 您是否尝试过仅导入商店import store from '@/store'
  • @SergeyMitrichev TypeError: Cannot read property 'state' of undefined, 刚刚在 router.js 文件中添加了 import store from '@/store' 并尝试访问 beforeEach 中的状态变量
  • import store from '@/store' import store from './store' 没有任何效果 第二个有这个错误 No default export found in import module "./store"

标签: javascript nuxt.js vue-router


【解决方案1】:

您可以通过根上下文访问商店,Nuxt 在 Vue 组件之外的 window.$nuxt 中提供了该上下文:

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

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 2020-12-07
    • 2019-03-05
    • 2021-06-03
    • 2018-11-23
    • 2018-05-19
    • 2019-11-04
    • 2020-08-25
    • 2020-02-05
    相关资源
    最近更新 更多