JAVASCRIPT

Dynamic Routing and Programmatic Navigation with Vue Router 4

Master creating dynamic routes and navigating programmatically using `router.push()` in Vue Router 4, essential for modern single-page applications.

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import UserProfile from '../views/UserProfile.vue';

const routes = [
  { path: '/', name: 'Home', component: Home },
  { path: '/user/:id', name: 'UserProfile', component: UserProfile, props: true }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;

// src/views/UserProfile.vue
<template>
  <div>
    <h2>User Profile</h2>
    <p>User ID: {{ userId }}</p>
    <button @click="goBack">Go Back</button>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';
import { computed } from 'vue';

const route = useRoute();
const router = useRouter();

// Access route parameters
const userId = computed(() => route.params.id);

// Programmatic navigation
const goBack = () => {
  router.back(); // or router.push({ name: 'Home' });
};
</script>

// src/App.vue (example usage)
<template>
  <div>
    <router-link to="/">Home</router-link> |
    <router-link :to="{ name: 'UserProfile', params: { id: 123 } }">User 123</router-link> |
    <button @click="navigateToUser(456)">Go to User 456</button>
    <router-view />
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();

const navigateToUser = (id) => {
  router.push({ name: 'UserProfile', params: { id } });
};
</script>
How it works: This snippet illustrates how to define dynamic routes and navigate programmatically using Vue Router 4. The `router/index.js` file sets up a route for user profiles with a dynamic `id` parameter. The `UserProfile.vue` component uses `useRoute` to access this parameter and `useRouter` for programmatic navigation (e.g., `router.back()`). The `App.vue` shows both declarative navigation with `router-link` and programmatic navigation using `router.push()` to send the user to a specific profile based on an ID.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs