我正在尝试学习Vuex并制作身份验证模块。我正在关注一些教程,并指出了要在路由器中使用存储的问题。 我将我的商店导入到路由器index.js的顶部,但是我猜它没有导入我的商店,因为我无法访问例如吸气剂(未定义)。
存储在vue组件中工作正常。为什么会这样呢?是因为创建路由器时未正确初始化存储区?根据很好的教程。
router / 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
}
和store / 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
}
答案 0 :(得分:1)
我会自己回答。我的商店没有典型的导出默认商店,
因此我将其修改为以下内容,并且工作正常。
const store = new Vuex.Store({
modules: {
authentication
},
namespaced: true,
strict: process.env.DEV,
})
export default store
答案 1 :(得分:1)
您不需要修改默认的Quasar store / index.js
只需将其用作Promise函数:
import store from '../store'
....
if (store().getters['auth/isLoggedIn']) {
next()
return
}