vue 登录验证引擎
1、router配置:
路由元信息 const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, children: [ { path: 'bar', component: Bar, // a meta field meta: { requiresAuth: true } } ] } ] }) // 父路由的配置可影响到子路由 { path: '/', name: 'index', redirect: './Home', component: r => require.ensure([], () => r(require('../components/Index')), 'Index'), meta: {requiresAuth: true}, children: [ { path: 'Home', component: r => require.ensure([], () => r(require('../components/home/Home')), 'Home') }, { path: 'CentralizedManager', component: r => require.ensure([], () => r(require('../components/centralizedmanager/CentralizedManager')), 'CentralizedManager') }, { path: 'Patrol', component: r => require.ensure([], () => r(require('../components/patrol/Patrol')), 'Patrol') }, ] }
router.beforeEach((to, from, next) => {
// 父路由的配置可影响到子路由 if (to.matched.some(record => record.meta.requiresAuth)) { // this route requires auth, check if logged in // if not, redirect to login page. if (!homeService.loggedIn()) { next('/Login') } else { next() } } else { next() // 确保一定要调用 next() } })
2、homeService :
loggedIn(){ return !!sessionStorage.getItem('accessToken'); },
3、登录
this.$http.post(url,data).then((response) => { if(result.code==100){ sessionStorage.setItem('accessToken', result.data.access_token); sessionStorage.setItem('userName', result.data.username); this.$notify({title: '成功',message: '登陆成功',type: 'success'}); this.$router.push('home') } }