vue.js - 在 Vue 路由解析之前访问 Vuex
问题描述
我有什么:
- 具有需要身份验证的路由和公共路由的路由器
- 具有用户身份验证状态的 vuex
我想要什么:在加载应用程序之前(在解析路由器之前)向服务器发送请求以检查用户axios
的身份验证状态。
router.js
:
import Vue from 'vue'
import Router from 'vue-router'
import store from './store'
Vue.use(Router)
const router = new Router({
...
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/account',
name: 'account',
component: () => import(/* webpackChunkName: "account" */ './views/Account.vue'),
meta: {
requiresAuth: true
}
}
]
})
router.beforeEach((to, from, next) => {
if (to.matched.some(route => route.meta.requiresAuth)) {
if (store.state.authStatus)
next()
else
next({name: 'home'})
} else {
next()
}
})
export default router
store.js
:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
authStatus: false
},
mutations: {
setAuthStatus(state, authStatus) {
state.authStatus = authStatus
}
}
})
axios.get(...)
.then(response => {
store.commit('setAuthStatus', true)
})
export default store
main.js
:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
我的问题:当我mydomain.com/acount
在被授权时进入浏览器(之前未加载应用程序)时,无论如何我被重定向到home
. 重定向后,我看到我已获得授权(我在 Home 组件中设置了一些 DOM 元素,仅对授权用户显示)。
我试过这个,没有帮助:
store.js
:
const store = new Vuex.Store({
...
actions: {
setAuthStatus({commit}) {
axios.get(...)
.then(response => {
commit('setAuthStatus', true)
})
}
}
})
main.js
:
store.dispatch('setAuthStatus').then(() => {
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
})
编辑:在main.js
我试图从
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
至
new Vue({
store,
router,
render: h => h(App)
}).$mount('#app')
它也没有帮助。
解决方案
绕过Vanojx1 的答案,我接下来解决了我的问题。
store.js
:
const store = new Vuex.Store({
state: {
authStatus: axios.get(...).then(response => {
store.commit('setAuthStatus', true)
}),
userAuth: false
},
mutations: {
setAuthStatus(state, authStatus) {
state.userAuth = authStatus
}
}
})
router.js
:
router.beforeEach((to, from, next) => {
if (to.matched.some(route => route.meta.requiresAuth)) {
store.state.authStatus.then(() => {
//we're getting 200 status code response here, so user is authorized
//be sure that API you're consuming return correct status code when user is authorized
next()
}).catch(() => {
//we're getting anything but not 200 status code response here, so user is not authorized
next({name: 'home'})
})
} else {
next()
}
})
推荐阅读
- android - 以编程方式将事件添加到日历
- json - 在使用 React Native 的某些记录后无法将值保存到 localMongoDB
- android - 如何将 android 模块用作应用程序和库
- java - How to extract the dynamic values of the id attributes of the table elements using Selenium and Java
- shopify - 关于“主题获取”命令 shopify 的问题
- gradle - 如何从 Gradle Kotlin DSL 表达式中访问项目版本?
- angular - 路由到具有不同参数的相同网址后,页面上的数据未更新
- reactjs - 如何修复反应表中的分页重置问题?
- sql - 通过调用存储过程更新表的 Null 记录会引发错误“子查询返回多个值”
- php - 如何解决这个问题“未定义的变量:类别”?