前言:

本篇为使用导航守卫和路由元信息编写的demo,用途是做拦截和询问,本篇中涉及的知识在上篇及上几篇中均有详细说明。如果对于某些知识不是很了解可以到前面的篇章中学习,或者留言给我。
源码地址:https://github.com/coder-Wang...
clone时切换到分支6.导航守卫拦截,具体操作:

git clone -b 6.导航守卫拦截 https://github.com/coder-WangYu/vue-test-code.git

1.先看看效果

1.1 访问控制

image

1.2 登录

image

1.3 访问需要权限页面

image

1.4 离开询问

image

2.源码解读

其实很简单,但这里还是说几个关键点吧。
router.js:
路由配置:

{
  path: '/about',
  component: () => import("../components/about.vue"),
  meta: {
    requestFlag: false,
    leaveFlag: true,
  },
},
{
  path: '/hy',
  component: () => import("../components/hy.vue"),
  redirect: '/hy/jd',
  children: [
    {
      path: 'jd',
      component: () => import("../components/hy/jd.vue"),
      meta: {
        requestFlag: true,
      },
    },
  ],
  meta: {
    requestFlag: true,
  },
},  
{
  path: '/login',
  component: () => import("../components/login.vue")
},

全局守卫:

router.beforeEach((to, from, next) => {
  let haveFlag = to.matched.some(item => item.meta.requestFlag)
  if (haveFlag) {
    document.cookie.includes('=') ? next() : window.confirm("需要登录才能浏览,是否登录?") ? next('/login') : next(false)
  } else {
    next()
  }
})

login.vue:

<template>
  <div class="login">
    <input placeholder="请输入用户名:" v-model="username"/>
    <input placeholder="请输入密码:" type="password" v-model="userpwd"/>
    <button type="button" @click="submitInfos">提交</button>
    <button type="button" @click="resetInfos">重置</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      userpwd: '',
    }
  },
  methods: {
    submitInfos() {
      document.cookie = this.username + '=' + this.userpwd
      window.confirm(`欢迎您${this.username},是否回到刚才的页面?`) ? this.$router.go(-1) : this.$router.go(0)
    },
    resetInfos() {
      this.username = ''
      this.userpwd = ''
    }
  }
}
</script>

about.vue:

<template>
  <div class="about">
    关于
  </div>
</template>

<script>
export default {
  beforeRouteLeave : (to, from, next) => {
    from.meta.leaveFlag ? window.confirm("确定残忍离开?") ? next() : next(false) : next()
  }
}
</script>

首先,在router.js中,使用全局守卫进行拦截,这样能够降低代码的冗余度。虽然组件内守卫和路由独享守卫也能实现这样的效果,但同样的代码会出现很多次。所以全局守卫最为适用。

其次,在嵌套路由中设置meta时,需要为其子路由也设置meta;因为如果只在父级路由中设置meta,那么通过在地址栏中输入子路由的path的方式也能够自由的进入。

在读写cookie时,通常是由后端完成的,为了实现效果,就如代码中所示的操作了。还请不要学我!!!

后序:

关于路由,预计再有两章就结束了。希望我的VueRouter中的内容还算充实,也希望能够给看到这些文章的朋友带来帮助。最后如果文章或源码有问题请及时留言,互帮互助才能不断进步!谢谢各位看官了~~~


Keep foolish, keep hungry.


野望
18 声望4 粉丝

一个为了写出漂亮代码而努力的前端人