您好,登录后才能下订单哦!
本篇文章给大家分享的是有关使用vue路由怎么实现一个登录拦截功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
vue-router提供了导航钩子:全局前置导航钩子 beforeEach和全局后置导航钩子 afterEach,他们会在路由即将改变前和改变后进行触发。所以判断用户是否登录需要在beforeEach导航钩子中进行判断。
导航钩子有3个参数:
1、to:即将要进入的目标路由对象;
2、from:当前导航即将要离开的路由对象;
3、next :调用该方法后,才能进入下一个钩子函数(afterEach)。
next()//直接进to 所指路由
next(false) //中断当前路由
next('route') //跳转指定路由
next('error') //跳转错误路由
这里用一个空白的vue项目来演示一下,主要有2个页面,分别是首页和登录。
访问首页时,必须要登录,否则跳转到登录页面。
新建一个空白的vue项目,在src\components创建Login.vue
<template> <div>这是登录页面</div> </template> <script> export default { name: "Login" } </script> <style scoped> </style>
修改src\router\index.js
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import Login from '@/components/Login' Vue.use(Router) const router = new Router({ mode: 'history', //去掉url中的# routes: [ { path: '/login', name: 'login', meta: { title: '登录', requiresAuth: false, // false表示不需要登录 }, component: Login }, { path: '/', name: 'HelloWorld', meta: { title: '首页', requiresAuth: true, // true表示需要登录 }, component: HelloWorld }, ] }) // 路由拦截,判断是否需要登录 router.beforeEach((to, from, next) => { if (to.meta.title) { //判断是否有标题 document.title = to.meta.title; } // console.log("title",document.title) // 通过requiresAuth判断当前路由导航是否需要登录 if (to.matched.some(record => record.meta.requiresAuth)) { let token = localStorage.getItem('token') // console.log("token",token) // 若需要登录访问,检查是否为登录状态 if (!token) { next({ path: '/login', query: { redirect: to.fullPath } }) } else { next() } } else { next() // 确保一定要调用 next() } }) export default router;
说明:
在每一个路由中,加入了meta。其中requiresAuth字段,用来标识是否需要登录。
在router.beforeEach中,做了token判断,为空时,跳转到登录页面。
访问首页
http://localhost:8080
会跳转到
http://localhost:8080/login?redirect=%2F
效果如下:
打开F12,进入console,手动写入一个token
localStorage.setItem('token', '12345678910')
效果如下:
再次访问首页,就可以正常访问了。
打开Application,删除Local Storage里面的值,右键,点击Clear即可
以上就是使用vue路由怎么实现一个登录拦截功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。