VueJs (Quasar), vuex store access in router
我正在尝试学习Vuex并制作身份验证模块。我正在关注一些教程,并指出了要在路由器中使用存储的问题。
我将我的商店导入到路由器index.js的顶部,但是我猜它没有导入我的商店,因为我无法访问例如吸气剂(未定义)。
存储在vue组件中工作正常。为什么会这样呢?是因为创建路由器时未正确初始化存储区?根据可以正常工作的教程。
router / index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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 } |
和store / index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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 } |
您不需要修改默认的Quasar store / index.js
只需将其用作Promise函数:
1 2 3 4 5 6 | import store from '../store' .... if (store().getters['auth/isLoggedIn']) { next() return } |
我会自己回答。我的商店没有典型的导出默认商店,
所以我将其修改为以下内容,并且工作正常。
1 2 3 4 5 6 7 8 9 | const store = new Vuex.Store({ modules: { authentication }, namespaced: true, strict: process.env.DEV, }) export default store |