vue项目路由重定向

2020-09-15  本文已影响0人  变量只提升声明不提升赋值

有时,我们可能会输入错的 url, 或者不再存在等各种原因导致其不再能被访问,那么我们就可以对于这种情况进行重定向。 很简单,只要在路由中添加下面的代码就可以了

//创建路由对象并配置路由规则
let router = new VueRouter({
    routes:[
       {path:'/',redirect:{name:"home"}},  // 重定向到主页
       {name:'home',path:'/home',component:Home},
       {path:'/music',component:Music},
       {path:'/movie',component:Movie},
       {name:'img',path:'/picture22',component:Picture},
       {name:'musicDetail',path:'/musicDetail/:id/:name',component:MusicDetail},
       {path:'*',component:NotFound},//全不匹配的情况下,返回404,路由按顺序从上到下,依次匹配。最后一个*能匹配全部,
    ]
});

也可以这样 注意放到routers里的最后

{
      path: "*",
      redirect: "/"
}

当重定向没办法很好的解决问题的时候 以下方法也可以适用

通过路由全局守卫

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

猜你喜欢

热点阅读