当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue 利用路由守卫判断是否登录的方法

vue 利用路由守卫判断是否登录的方法

2018年10月07日  | 移动技术网IT编程  | 我要评论

妖道之纵横江湖,遍地狼烟演员表,秀阴吧

1.在router下的index.js 路由文件下,引入相关需要文件;

import vue from 'vue'

import router from 'vue-router'
import {login} from '../common/js/islogin'
import helloworld from '@/components/helloworld'
import login from '@/page/login'
import index from '@/page/index/index'vue.use(router);

2.配置相关路由

const router = new router({

 routes: [
 {
  path: '/',
  redirect: '/login'
 },
 {
  path: '/login',
  component: login
 },
 {
  path: '/index',
  meta: {
  requireauth: true, // 添加该字段,表示进入这个路由是需要登录的
  },
  component: index
 }
 ]
});

3.路由配置完后,根据需要登录的页面判断路由跳转

router.beforeeach((to, from, next) => {
 if (to.meta.requireauth) {   //如果需要跳转 ,往下走(1)
 if (true) {   //判断是否登录过,如果有登陆过,说明有token,或者token未过期,可以跳过登录(2)
  if (to.path === '/login') { //判断下一个路由是否为要验证的路由(3)
  next('/index');   // 如果是直接跳到首页,
  } else {    //如果该路由不需要验证,那么直接往后走
  next();
  }
 } else {
  console.log('没有');  //如果没有登陆过,或者token 过期, 那么跳转到登录页
  next('/login');
 }
 } else {       //不需要跳转,直接往下走
 next();
 }
});export default router;

以上这篇vue 利用路由守卫判断是否登录的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网