Programmatic navigation lets you change pages in your app using code, not just links. This helps when you want to move users automatically after actions like login or form submission.
0
0
Programmatic navigation with useRouter in Vue
Introduction
After a user logs in, redirect them to their dashboard.
When a form is successfully submitted, navigate to a confirmation page.
Automatically send users to a login page if they try to access a protected page.
Navigate to a details page when a user clicks a button instead of a link.
Syntax
Vue
import { useRouter } from 'vue-router' const router = useRouter() // To navigate to a new route router.push('/path') // Or with route name and params router.push({ name: 'routeName', params: { id: 123 } })
useRouter is a function from vue-router that gives you access to navigation methods.
router.push() changes the page programmatically.
Examples
Navigate to the '/home' URL path.
Vue
router.push('/home')Navigate to a named route 'profile' with a parameter userId=42.
Vue
router.push({ name: 'profile', params: { userId: 42 } })Navigate using an object with a path property.
Vue
router.push({ path: '/about' })Sample Program
This Vue component shows a button. When clicked, it uses useRouter to navigate to the '/dashboard' page programmatically.
Vue
<script setup> import { useRouter } from 'vue-router' const router = useRouter() function goToDashboard() { router.push('/dashboard') } </script> <template> <button @click="goToDashboard" aria-label="Go to Dashboard">Go to Dashboard</button> </template>
OutputSuccess
Important Notes
Always import useRouter from vue-router before using it.
Programmatic navigation does not reload the page; it changes the route inside your app.
Use router.push() for normal navigation and router.replace() if you want to replace the current history entry.
Summary
Programmatic navigation lets you move users between pages using code.
useRouter provides the router.push() method to change routes.
This is useful for redirects after actions like login or form submission.