首页 > 解决方案 > VueJs (Quasar),路由器中的 vuex 存储访问

问题描述

我正在尝试学习 Vuex 并制作身份验证模块。我正在学习一些教程,并达到了我想在路由器中使用商店的目的。我在路由器 index.js 的顶部导入我的商店,但是我猜它没有导入我的商店,因为我无法访问例如 getter(未定义)。

Store 在 Vue 组件中运行良好。为什么会这样?是因为创建路由器时商店没有正确初始化吗?根据教程,效果很好。

路由器/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '../store'
Vue.use(VueRouter)

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation
 */

export default function(/* { store, ssrContext } */) {
  const Router = new VueRouter({
    scrollBehavior: () => ({ x: 0, y: 0 }),
    routes,
    // Leave these as is and change from quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    mode: process.env.VUE_ROUTER_MODE,
    base: process.env.VUE_ROUTER_BASE,
  })
  Router.beforeEach((to, from, next) => {
    if(to.matched.some(record => record.meta.requiresAuth)) {

      if (store.getters.isLoggedIn) {
        next()
        return
      }
      next('/login')
    } else {
      next()
    }
  })
  return Router
}

和存储/index.js

import Vue from 'vue'
import Vuex from 'vuex'

// import example from './module-example'

Vue.use(Vuex)
/*
 * If not building with SSR mode, you can
 * directly export the Store instantiation
 */
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'


export default function(/* { ssrContext } */) {
  const Store = new Vuex.Store({
    modules: {
      // example
    },
    namespaced: true,
    getters,
    mutations,
    actions,
    state,
    // enable strict mode (adds overhead!)
    // for dev mode only
    strict: process.env.DEV,
  })

  return Store
}

标签: javascriptvue.jsvuexstorerouter

解决方案


您不需要修改默认的 Quasar store/index.js

只需将其用作 Promise 函数:

import store from '../store'
....
if (store().getters['auth/isLoggedIn']) {
   next()
   return
}

推荐阅读