tezvyn:

Programmatic Navigation: Changing Routes with Code

AI-drafted, machine-checkedSource: router.vuejs.orgbeginner

Instead of a user clicking a link, you trigger navigation from your JavaScript. This is useful for redirecting after an action, like a successful login. The main footgun: `params` are ignored if you also provide a `path`—use a named route instead.

WHY IT EXISTS Single-page applications need to change the displayed 'page' without a full browser reload. While user-clicked links handle most cases, some navigation must be triggered by application logic, not direct user interaction, such as redirecting after a successful API call.

THE MENTAL MODEL Think of programmatic navigation as a remote control for the browser's address bar. Instead of the user clicking a link (declarative navigation), your code decides when and where to go next. This is crucial for guiding users through a flow, like redirecting from a login page to a dashboard.

HOW IT WORKS You access the router instance (via this.$router or useRouter()) and call its methods. The three main methods are: first, router.push(), which navigates to a new location and adds it to the browser's history stack; second, router.replace(), which navigates but replaces the current history entry, so the back button won't return to the previous page; and third, router.go(n), which moves forward or backward in the history stack.

WHEN TO USE IT Use programmatic navigation when a URL change is the result of an event or a process. Common scenarios include: after a user successfully logs in, redirecting them to their profile; after a form submission, sending them to a confirmation page; or programmatically sending a user to a 404 page if data fails to load.

WHEN NOT TO USE IT For any standard navigation that a user is meant to initiate directly, prefer declarative navigation with <router-link>. It's more accessible, semantic, and clearly indicates a link to users and search engines. Don't use router.push() for every link on your site; reserve it for logic-driven redirects.

ONE CANONICAL EXAMPLE A classic footgun is trying to pass route parameters with a path. The router will ignore the parameters. For example, router.push({ path: '/user', params: { id: 123 } }) is wrong and results in the URL '/user'. The correct way is to use a named route: router.push({ name: 'user-profile', params: { id: 123 } }). This correctly generates the URL '/user/123' because the router uses the route's name to find the correct path structure and inject the parameters.

Read the original → router.vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.