1.所有路由匹配

路由的匹配规则是按照书写的顺序执行的,第一条匹配成功则不去匹配下一条,利用这一特性,可以在所有匹配路由的下面拦截匹配所有路由:

Vue.use(Router);
const router = new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      redirect: '/home',
      component: home,
      meta: {
        footShow: true // true显示,false隐藏
      }
    },
    {
      path: '/home',
      name: 'home',
      component: home,
      meta: {
        footShow: true // true显示,false隐藏
      }
    },
    { // 当没有匹配到正确路由的时候,匹配notOpen组件
      path: '*',
      component: notOpen,
      meta: {
        footShow: false // true显示,false隐藏
      }
    }
}

2.重定向

Vue.use(Router);
const router = new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      redirect: '/home',
      component: home,
      meta: {
        footShow: true // true显示,false隐藏
      }
    },
    {
      path: '/home',
      name: 'home',
      component: home,
      meta: {
        footShow: true // true显示,false隐藏
      }
    },
    { // 当没有匹配到正确路由的时候,匹配notOpen组件
      path: '*',
      redirect: notOpen,
      meta: {
        footShow: false // true显示,false隐藏
      }
    }
}

3.导航守卫

router.beforeEach((to, from, next) => {
  if (to.matched.length ===0) {  //如果未匹配到路由
    from.path? next({ path:from.path}) : next('/notOpen');   //如果上级也未匹配到路由则跳转主页面,如果上级能匹配到则转上级路由
  } else {
    next();    //如果匹配到正确跳转
  }
});

 

Logo

前往低代码交流专区

更多推荐