当做Vue-cli项目的时候感觉在路由跳转前做一些验证,比如登录验证,是网站中的普遍需求。
对此,vue-router 提供的 beforeEach可以方便地实现全局导航守卫(navigation-guards)。组件内部的导航守卫函数使用相同,只是函数名称不同(beforeRouteEnter 、beforeRouteUpdate(2.2 新增) 、beforeRouteLeave)。

官方文档地址:https://router.vuejs.org/zh-cn/advanced/navigation-guards.html

如何设置一个全局守卫

你可以使用 router.beforeEach 注册一个全局前置守卫:就是在你router配置的下方注册

  1. const router = new VueRouter({ ... })
  2. router.beforeEach((to, from, next) => {
  3. // ...
  4. })

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中

每个守卫方法接收三个参数:

  • to: Route: 即将要进入的目标 路由对象

  • from: Route: 当前导航正要离开的路由

  • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

    • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

    • next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

    • next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: truename: 'home' 之类的选项以及任何用在 router-linkto proprouter.push 中的选项。

    • next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

确保要调用 next 方法,否则钩子就不会被 resolved。

一个简单实用的小例子:

  1. const router = new VueRouter({ ... }) //这是路由配置,我就不多说了
  2. const whiteList = ['/error', '/register/regindex', '/register/userauthent', '/register/submit'] // 路由白名单
  3. vueRouter.beforeEach(function(to,from,next){
  4. console.log("进入守卫");
  5. if (userInfo.user_id>0){
  6. console.log("登录成功");
  7. next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
  8. }else{
  9. console.log("登录失败");
  10. getUserInfo.then(res => {
  11. if(res){
  12. if (res.user_id){
  13. if (res.status == 4) {
  14. //账号冻结
  15. next({ path: '/error', replace: true, query: { noGoBack: true } })
  16. }
  17. if (res.status == 3) {
  18. //认证审核中
  19. next({ path: '/register/submit', replace: true, query: { noGoBack: true } })
  20. }
  21. if (res.status != 1 && res.status != 3) {
  22. if (!res.mobile ) {
  23. next({ path: '/register/regindex', replace: true, query: { noGoBack: true }})
  24. } else {
  25. //绑定完手机号了
  26. next({ path: '/register/userauthent', replace: true, query: { noGoBack: true } })
  27. }
  28. }
  29. next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
  30. }else{
  31. if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
  32. next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
  33. }else{
  34. next({ path: '/register/regindex', replace: true, query: { noGoBack: true }})
  35. }
  36. }
  37. }else{
  38. }
  39. }
  40. }).catch(()=>{
  41. //跳转失败页面
  42. next({ path: '/error', replace: true, query: { noGoBack: true }})
  43. })
  44. }
  45. });
  46. export default router

温馨提示:有些地方为vuex介入调取方法及数据判断,但由于例子原因就不展示,只提供思路供大家参考。

最后和大家说下如果白名单太多或项目更大时,我们需要把白名单换为vue-router路由元信息:

meta字段(元数据)

直接在路由配置的时候,给每个路由添加一个自定义的meta对象,在meta对象中可以设置一些状态,来进行一些操作。用它来做登录校验再合适不过了

  1. {
  2. path: '/actile',
  3. name: 'Actile',
  4. component: Actile,
  5. meta: {
  6. login_require: false
  7. },
  8. },
  9. {
  10. path: '/goodslist',
  11. name: 'goodslist',
  12. component: Goodslist,
  13. meta: {
  14. login_require: true
  15. },
  16. children:[
  17. {
  18. path: 'online',
  19. component: GoodslistOnline
  20. }
  21. ]
  22. }

这里我们只需要判断item下面的meta对象中的login_require是不是true,就可以做一些限制了

  1. router.beforeEach((to, from, next) => {
  2. if (to.matched.some(function (item) {
  3. return item.meta.login_require
  4. })) {
  5. next('/login')
  6. } else
  7. next()
  8. })

.

Vue中的导航守卫(路由守卫)的更多相关文章

  1. Vue中使用children实现路由的嵌套

    Vue中使用children实现路由的嵌套 相关Html: <!DOCTYPE html> <html lang="en"> <head> &l ...

  2. vue中的导航守卫

    官方文档地址: 导航守卫:https://router.vuejs.org/zh-cn/advanced/navigation-guards.html 好的,重点内容 router.beforeEac ...

  3. vue学习(9)-路由守卫

    全局守卫 你可以使用 router.beforeEach 注册一个全局前置守卫: const router = new VueRouter({ ... })   router.beforeEach(( ...

  4. vue的生命周期和路由守卫

    组件相关钩子函数: beforeCreate.created.beforeMount.mounted.beforeUpdate.updated.beforeDestroy.destoryed   还有 ...

  5. vue中如何不通过路由直接获取url中的参数

    前言:为什么要不通过路由直接获取url中的参数? vue中使用路由的方式设置url参数,但是这种方式必须要在路径中附带参数,而且这个参数是需要在vue的路由中提前设置好的. 相对来说,在某些情况下直接 ...

  6. 【Vue中的坑】路由相同参数不同无法触发路由

    场景: vue实现导航栏,二级导航栏跳转到相同页面,通过参数来实现到该页面后,根据参数来滚动到对应到位置 网上的解决方法: 通常情况下我们喜欢设置keepAlive 包裹 router-view &l ...

  7. Vue中添加新的路由并访问

    1.搭建好Vue脚手架(这里使用的版本是Vue2.0) 2.在代码编辑器(这里使用的是Sublime Text)打开项目文件夹 3.在文件目录src中的component下创建一个新的vue页面,写入 ...

  8. 064——VUE中vue-router之使用路由别名定制(alias)

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. Vue中的组件及路由使用

    1.组件是什么        组件系统是 Vue 的一个重要概念,因为它是一种抽象,允许我们使用小型.独立和通常可复用的组件构建大型应用.通常一个应用会以一棵嵌套的组件树的形式来组织: 1.1组件的声 ...

随机推荐

  1. Mysql字符串截取_获取指定字符串中的数据

    前言:本人遇到一个需求,需要在MySql的字段中截取一段字符串中的特定字符,类似于正则表达式的截取,苦于没有合适的方法,百度之后终于找到一个合适的方法:substring_index('www.sql ...

  2. Windows CLI命令

    目录 Windows CLI命令 1.背景 2.netstat 罗列端口号占用情况 3.telnet 远端IP的某个端口号 Windows CLI命令 1.背景 在Windows操作系统下开发,需要用 ...

  3. Logo(图片)作为报表水印的解决方法

    概述 在<像 word 一样增加水印功能>中,已经介绍了如何在润乾报表中增加文字水印功能,包括了静态及动态水印.水印功能将标识信息嵌入到报表载体后,使得信息安全.版权保护有了更有效的方法. ...

  4. 3、nio中的selector使用

    通过编写一个客户端和服务器端的例子来熟悉selector的使用 服务端逻辑: 1. 绑定一个端口号2. channel注册到selector中3. 用死循环来监听如果有时间发生,遍历selection ...

  5. This system is not registered with ULN

    [root@DBDATA yum.repos.d]# yum makecacheLoaded plugins: aliases, changelog, downloadonly, fastestmir ...

  6. Error:Cannot build artifact 'ssm:war exploded' because it is included into a circular dependency (artifact 'ssm:war exploded', artifact 'apinb-master:war exploded')

    打开 File->Project Structure –> Artifacts(ctrl+alt+shift+s) ,这里会有4个,我已经删除了,把 ssm:war 和 ssm:war e ...

  7. @ImportResource

    1. @ImportResource(locations = {"classpath:beantest.xml"})标注到启动类上,从类路径下加载xml文件,通过Applicati ...

  8. fiddler抓包的一些基本知识整理

    fiddler常用命令:selelct xx: 高亮显示所有的text,js,image等响应类型?xxx:匹配所有url.protocol.host中包含xxx的会话=404:选择响应状态码为404 ...

  9. Java之Lambda表达式

    函数式编程思想概述 面向对象过分强调“必须通过对象的形式来做事情”,而函数式思想则尽量忽略面向对象的复杂语法——强调做什么,而不是以什么形式做. 面向对象的思想: 做一件事情,找一个能解决这个事情的对 ...

  10. my-eclipse 安装与下载

    百度网盘下载 链接:https://pan.baidu.com/s/13FFcVLyofd2TBP0zun0zTg 提取码:8ofg MyEclipse CI 2019是一个十分优秀的用于开发Java ...