美文网首页Vue.js
vue-router的使用(二)路由检测访问权限

vue-router的使用(二)路由检测访问权限

作者: 尤樊容 | 来源:发表于2019-04-28 16:29 被阅读1次

    路由检测访问权限

    你可以在组件做判断是否可以访问该链接,也可以在打开路由之前就判断是否能够访问,后者是比较好的实现方式,简洁明了。

    //相当于一个中间件,在正式打开组件之前,做一些判断
    router.beforeEach(function (to, from, next) {
      //其中
      next();//继续执行
      next(false);//不往下执行
      next('/');//跳转到其他页
    });
    

    参数分析:
    to:要去的页
    from: 当前的页(来的页)
    next:回调函数

    router.beforeEach(function (to, from, next) {
       let bool = false;
      //满足一定的条件再跳转
       if(!bool && to.path == 'user'){
          next('/');
      }else{
        next();
      }
    });
    

    除了beforeEach,相对应的还有一个afterEach,具体使用如下:

    router.afterEach(function (to, from) {
      //在这个地方你可以放一些请求或者进入界面后需要做的事情,
      //当然也是可以直接放在组件里的,是情况而定
    });
    

    在满足一定条件再渲染的时候有个地方需要注意的是,访问的‘/user’,后面还有路由,比如:‘/user/name’,如果还是使用上面的判断方式就会有问题,在'/user/name'的时候照样可以访问,并没有被阻止,这就不够严谨了。
    解决办法:
    to有一个属性叫matched,这个里面包含了所有的子路由,所以可以这么做:

    router.beforeEach(function (to, from, next) {
       let bool = false;
      //some只要其中一个为true 就会返回true的
       if(!bool && to.matched.some(function(item){
          return item.path=='/user';
       })){
          next('/');
       }else{
          next();
       }
    });
    

    但是如果有很多需要限制的界面,如果每个都要去判断、遍历就会很麻烦,下面就来解决一下这个问题:
    在对应需要限制的路由里加上一个属性meta:

    let route = new VueRouter({
      routes:[{
        path: '/user/page1',
        name: 'user',
        meta: {
          is_next_show: false
        },
        component: User,
        children:[{
          path:'more',
          component:More
        }]
      }]
    });
    

    对应修改:

    router.beforeEach(function (to, from, next) {
       let bool = false;
      //some只要其中一个为true 就会返回true的
       if(!bool && to.matched.some(function(item){
          return item.meta.is_next_show;
       })){
          next('/');
       }else{
          next();
       }
    });
    

    或者有很多界面都需要限制的时候,就很方便了,如下:

    let route = new VueRouter({
      routes:[{
        path: '/user/page1',
        name: 'user',
        meta: {
          is_next_show: false
        },
        component: User,
        children:[{
          path:'more',
          component:More
        }]
      },{
        path: '/aaa',
        name: 'aaa',
        meta: {
          is_next_show: false
        },
        component: Aaa,
      },{
        path: '/bbb',
        name: 'bbb',
        component: Bbb,
      }]
    });
    

    只有aaa和user被限制,因为只有这两个路由有对应属性。

    相关文章

      网友评论

        本文标题:vue-router的使用(二)路由检测访问权限

        本文链接:https://www.haomeiwen.com/subject/vzcjnqtx.html