如何在Vue.js中借助Vuex实现全局路由保护并使用getToken
全局路由保护实现:用Vuex的getToken替代localStorage
问题背景
此前在单个路由中使用beforeRouteEnter钩子,通过localStorage获取token,无token时跳转登录页。现需改为全局路由保护,且使用Vuex store中的getToken getter获取token(已在Vuex中存储token),相关组件代码如下:
created() { this.getTokenFromStorage(); }, computed: { ...mapGetters(['currentUser', 'error', 'getToken']), }, methods: { ...mapActions(['getUser', 'getTokenFromStorage']), },
实现步骤
1. 配置全局路由前置守卫
找到路由配置文件(通常为router/index.js),导入Vuex store实例,通过router.beforeEach注册全局前置守卫:
import store from '@/store' // 根据你的store实际路径调整 const router = new VueRouter({ // 你的路由规则配置 }) router.beforeEach((to, from, next) => { // 从Vuex getter获取token const token = store.getters.getToken // 定义无需权限校验的路由白名单 const whiteList = ['/login'] if (token) { // 已登录状态:若跳转登录页,直接重定向到首页 if (to.path === '/login') { next('/') } else { // 未获取用户信息时,调用action拉取用户数据 if (!store.getters.currentUser) { store.dispatch('getUser').then(() => { next() }).catch(() => { // 获取用户信息失败,清除token并跳转登录页 store.dispatch('clearToken') // 需确保Vuex中有对应的清除token action next('/login') }) } else { next() } } } else { // 未登录状态:路由在白名单则放行,否则跳转登录页 whiteList.includes(to.path) ? next() : next('/login') } }) export default router
2. 确保token提前初始化
为保证路由守卫能拿到正确的token值,需在Vue实例创建时就执行getTokenFromStorage action,将localStorage中的token同步到Vuex:
// 在main.js中 new Vue({ router, store, created() { this.$store.dispatch('getTokenFromStorage') }, render: h => h(App) }).$mount('#app')
3. 补充Vuex必要action(若缺失)
如果Vuex中还没有清除token的action,需添加对应逻辑:
// 在store的对应模块或根store中 actions: { // 其他已存在的action... clearToken({ commit }) { commit('SET_TOKEN', null) // 需对应mutation修改token状态 localStorage.removeItem('token') // 同步清除localStorage中的token } }
注意事项
- 白名单需根据业务调整,比如注册页、404页等无需权限的页面都要加入
- 若
getUseraction依赖token,需确保token已存在再调用,避免无效请求 - 可根据需求扩展逻辑,比如增加token过期校验等
内容的提问来源于stack exchange,提问作者jibzy
相关产品推荐
相关产品推荐

