关于前端:VueRouter导航守卫拦截六

8次阅读

共计 1963 个字符,预计需要花费 5 分钟才能阅读完成。

前言:

本篇为应用导航守卫和路由元信息编写的 demo,用处是做拦挡和询问,本篇中波及的常识在上篇及上几篇中均有具体阐明。如果对于某些常识不是很理解能够到后面的篇章中学习,或者留言给我。
源码地址:https://github.com/coder-Wang…
clone 时切换到分支 6. 导航守卫拦挡,具体操作:

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

1. 先看看成果

1.1 访问控制

1.2 登录

1.3 拜访须要权限页面

1.4 来到询问

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.

正文完
 0