Vue Router(6)

重定向

 重定向也是通过 routes配置来完成,下面是 /home 重定向到 /:

const routes = [{ path: '/home', redirect: '/' }]

 

重定向的目标也可以是一个命名的路由

const routes = [{ path: '/home', redirect: { name: 'homepage' } }]

 

甚至是一个方法,动态返回重定向目标

const routes = [
  {
    // /search/screens -> /search?q=screens
    path: '/search/:searchText',
    redirect: to => {
      // 方法接收目标路由作为参数
      // return 重定向的字符串路径/路径对象
      return { path: '/search', query: { q: to.params.searchText } }
    },
  },
  {
    path: '/search',
    // ...
  },
]

 (注,导航守卫并没有应用在跳转路由上,而仅仅应用在其目标上,在上面的例子中,在 、home 路由中添加beforeEnter 守卫不会有任何效果

 

别名

重定向是指当用户访问 /home 时, URL会被 / 替换, 然后匹配成 /。 那什么是别名呢?

将 / 别名为 /home,意味着当用户访问 /home 时,URL仍然是 /home,但会被匹配为用户正在访问 /.

上面对应的路由配置为:

const routes = [{ path: '/', component: Homepage, alias: '/home' }]

posted on 2022-02-17 09:58  zhishiyv  阅读(36)  评论(0编辑  收藏  举报

导航