标签:com bsp import hello efault else default local pat
vue项目中登录状态判断往往基于jwt认证,我们可以采用以下两种方式来实现token状态的判断;
1.利用vue-router 钩子函数
import Vue from ‘vue‘ import Router from ‘vue-router‘ import HelloWorld from ‘@/components/HelloWorld‘ import home from ‘@/page/home‘ import store from ‘@/page/store‘ import login from ‘@/page/login‘ Vue.use(Router) const router = new Router({ routes: [ { path: ‘/home‘, name: ‘home‘, component: home, meta: { requireAuth: true }, }, { path: ‘/login‘, name: ‘login‘, component: login }, { path: ‘/store‘, name: ‘store‘, component: store, meta: { requireAuth: true }, } ] }) //判断是否登录 router.beforeEach((to, from, next) => { if (to.matched.some(res => res.meta.requireAuth)) { if (localStorage.getItem(‘token‘)) { next() } else { next({ path: ‘/login‘, query: { redirect: to.fullPath } }) } } else { next() } }); export default router
2.在需要认证登录状态的页面watch router对象
watch: { ‘$route‘: function(to, from,next) { if (to.matched.some(res => res.meta.requireAuth)) { if (window.localStorage.getItem(‘token‘)) { next() } else { next({ path: ‘/login‘, query: { redirect: to.fullPath } }) } } else { next() } } }
以上登录仅仅对前端是否存在token做了判断,实际项目中往往后端会对token设置有效时间,所以还需在axios请求中对后台返回的token信息过期的判断。后续附上详细代码
标签:com bsp import hello efault else default local pat
原文地址:https://www.cnblogs.com/zhuzeliang/p/9035053.html