une*_*asy 2 javascript router store vue.js 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
}
Run Code Online (Sandbox Code Playgroud)
和 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
}
Run Code Online (Sandbox Code Playgroud)
您不需要修改默认的 Quasar store/index.js
只需将其用作 Promise 函数即可:
import store from '../store'
....
if (store().getters['auth/isLoggedIn']) {
next()
return
}
Run Code Online (Sandbox Code Playgroud)