[Vue Router] Redirect & Alias

As our application evolves, we may need to change the URL paths of where our pages initially found. There are two convenience methods for this:

 

⚠️ Problem: Changing Routes

What if we needed to change our application from using /about for our about page to /about-us . How might we deal with this?

✅ Solution #1: Redirect

Obviously the first step is to change our original route:

    const router = new VueRouter({
      routes: [
        ...
        {
          path: '/about-us',
          name: 'About',
          component: About
        }
      ]
    })

If we’re using named routes then we don’t need to change our router-links at all. Otherwise we would have to. Then, since there might be links around the internet to our /about page, we want to make that redirect from /about to /about-us, with the following additional route.

 const router = new VueRouter({
      routes: [
        ...
        { 
          path: '/about', 
          redirect: { name: "About" }
        }
      ]
    })

Note we’re using the named route for the redirect. We could have also used redirect: "/about-us" to get the same functionality, but this is hard-coding a URL in one more place we’d have to change if the path changed.

https://firebasestorage.googleapis.com/v0/b/vue-mastery.appspot.com/o/flamelink%2Fmedia%2F1.1607724721632.gif?alt=media&token=9db43660-9344-49aa-bf6b-1f668e679a5a

 

✅ Solution #2: Alias

Instead of redirecting the old path we might just want to alias it, meaning just provide a duplicate path to the same content. We could update that path and provide an alias to the old path:

    const router = new VueRouter({
      routes: [
        ...
        {
          path: '/about-us',
          name: 'About',
          component: About,
          alias: '/about' // <-----
        }
      ]
    })

Now the user can go to /about or /about-us and they’ll get the same content.

https://firebasestorage.googleapis.com/v0/b/vue-mastery.appspot.com/o/flamelink%2Fmedia%2F2.1607724721633.gif?alt=media&token=c0696625-f0b0-4c57-9e54-ce727581d101

 

⚠️ Problem: Complex Routes

In the application we’ve been building in our Touring Vue Router course to view an event we go to /event/123. Some developers might prefer this URL to be /events/123, the plural. Let’s assume we want to make this change, and ensure that all our old URLs redirect properly to the new URL.

✅ Solution: Redirecting Dynamic Segments

To redirect a dynamic segment, we’ll need to get access to the params when we create the new path. To do this we’ll need to send in an anonymous function into the redirect property, like so:

📜 /src/router/index.js

...
const routes = [
  ...
  {
    path: '/events/:id', // <--- make plural 'events'
    name: 'EventLayout',
    ...
  },
  {
    path: '/event/:id',
    redirect: to => {
      return { name: 'EventDetails', params: { id: to.params.id } }
    }
  },

Notice how inside this anonymous function we could do some complex logic if needed. Turns out we can simplify what we wrote above, because the id param will get passed along automatically. Vue Router is smart like this:

{
    path: '/event/:id',
    redirect: () => {
      return { name: 'EventDetails' }
    }
},

 

✅ Redirect with children

It turns out that redirect has the ability to accept children. So we can do this:

 {
    path: '/event/:id',
    redirect: () => {
      return { name: 'EventDetails' }
    },
    children: [
      { path: 'register', redirect: () => ({ name: 'EventRegister' }) },
      { path: 'edit', redirect: () => ({ name: 'EventEdit' }) }
    ]
  },

 

✅ Redirect with Wildcard

Another way we could solve this is with a wildcard, like so:

{
    path: '/event/:afterEvent(.*)',
    redirect: to => {
      return { path: '/events/' + to.params.afterEvent }
    }
  },

This is taking whatever comes after the matching word /event/ and placing it after /events/. This is less code, and covers all children routes.

 

posted @   Zhentiw  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-11-26 [XState] raise event: trigger an action immediately when reach target state
2022-11-26 [Typescript] 118. Hard - IsRequiredKey
2022-11-26 [Typescript] 117. Hard - ClassPublicKeys
2020-11-26 [RxJS] Filtering operator: first
2020-11-26 [Tools] Interactively exploring a large JSON file with fx
2020-11-26 [Javascript] Broadcaster + Operator + Listener pattern -- 22. mapError, wrap fetch with broadcaster with cancellation
2020-11-26 [Javascript] Cancel a promise
点击右上角即可分享
微信分享提示