JAVASCRIPT
Dynamic Routing and Programmatic Navigation in Vue Router 4
Set up dynamic routes and navigate programmatically in Vue 3 applications using Vue Router 4, enhancing user experience and application structure.
// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import AboutView from '../views/AboutView.vue';
import UserProfile from '../views/UserProfile.vue';
const routes = [
{
path: '/',
name: 'Home',
component: HomeView
},
{
path: '/about',
name: 'About',
component: AboutView
},
{
path: '/users/:id',
name: 'UserProfile',
component: UserProfile,
props: true // Pass route params as component props
}
];
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
});
export default router;
// main.js (part of your app setup)
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
// App.vue (Main Layout)
<template>
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link to="/users/1">User 1 Profile</router-link> |
<router-link to="/users/2">User 2 Profile</router-link>
<button @click="goToRandomUser">Go to Random User (Programmatic)</button>
</nav>
<router-view />
</template>
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const goToRandomUser = () => {
const randomId = Math.floor(Math.random() * 10) + 1;
router.push({ name: 'UserProfile', params: { id: randomId } });
// Alternatively: router.push(`/users/${randomId}`);
};
</script>
// views/UserProfile.vue (Example Dynamic Component)
<template>
<div>
<h2>User Profile</h2>
<p>Viewing profile for User ID: {{ id }}</p>
<button @click="goBack">Go Back</button>
</div>
</template>
<script setup>
import { defineProps } from 'vue';
import { useRouter } from 'vue-router';
const props = defineProps({
id: { type: [String, Number], required: true }
});
const router = useRouter();
const goBack = () => {
router.back();
};
</script>
How it works: This snippet illustrates how to configure dynamic routes and perform programmatic navigation using Vue Router 4. In `router/index.js`, a dynamic route `/users/:id` is defined, where `:id` is a route parameter. `props: true` allows the parameter to be directly passed as a prop to the `UserProfile` component. `App.vue` uses `router-link` for declarative navigation and `useRouter()` to access the router instance for programmatic navigation (e.g., `router.push()` to navigate to a random user). `UserProfile.vue` receives the dynamic `id` as a prop and uses `router.back()` to navigate to the previous history entry.