javascript – 在定义Vue-Router路由时访问Vuex状态
作者:互联网
我有以下Vuex商店(main.js):
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//init store
const store = new Vuex.Store({
state: {
globalError: '',
user: {
authenticated: false
}
},
mutations: {
setGlobalError (state, error) {
state.globalError = error
}
}
})
//init app
const app = new Vue({
router: Router,
store,
template: '<app></app>',
components: { App }
}).$mount('#app')
我还为Vue-Router(routes.js)定义了以下路由:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//define routes
const routes = [
{ path: '/home', name: 'Home', component: Home },
{ path: '/login', name: 'Login', component: Login },
{ path: '/secret', name: 'Secret', component: SecretPage, meta: { requiresLogin: true }
]
我试图这样做,以便如果Vuex商店的用户对象已经过身份验证属性为false,请让路由器将用户重定向到“登录”页面.
我有这个:
Router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresLogin) && ???) {
// set Vuex state's globalError, then redirect
next("/Login")
} else {
next()
}
})
问题是我不知道如何从beforeEach函数内部访问Vuex商店的用户对象.
我知道我可以使用BeforeRouteEnter在组件内部使用路由器保护逻辑,但这会使每个组件混乱.我想在路由器级别集中定义它.
解决方法:
正如建议的here,您可以做的是从您所在的文件中导出您的商店并将其导入routes.js.它将类似于以下内容:
你有一个store.js:
import Vuex from 'vuex'
//init store
const store = new Vuex.Store({
state: {
globalError: '',
user: {
authenticated: false
}
},
mutations: {
setGlobalError (state, error) {
state.globalError = error
}
}
})
export default store
现在在routes.js中,您可以拥有:
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from ./store.js
Vue.use(VueRouter)
//define routes
const routes = [
{ path: '/home', name: 'Home', component: Home },
{ path: '/login', name: 'Login', component: Login },
{ path: '/secret', name: 'Secret', component: SecretPage, meta: { requiresLogin: true }
]
Router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresLogin) && ???) {
// You can use store variable here to access globalError or commit mutation
next("/Login")
} else {
next()
}
})
在main.js中你也可以导入商店:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import store from './store.js'
//init app
const app = new Vue({
router: Router,
store,
template: '<app></app>',
components: { App }
}).$mount('#app')
标签:vuex,vue-router,javascript,vue-js,vuejs2 来源: https://codeday.me/bug/20190930/1835285.html