← Back to all snippets
JAVASCRIPT

Configure Dynamic Routes and Programmatic Navigation in Vue Router 4

Master Vue 3 Router by defining routes with dynamic segments and performing programmatic navigation, crucial for building flexible single-page applications.

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

const routes = [
  {
    path: '/',
    name: 'Home',
    component: HomeView
  },
  {
    path: '/user/:id', // Dynamic segment :id
    name: 'UserProfile',
    component: UserProfile,
    props: true // Pass route params as props to the component
  },
  {
    path: '/about',
    name: 'About',
    // Route-level code splitting
    // this generates a separate chunk (About.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import('../views/AboutView.vue')
  }
];

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

export default router;

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

const app = createApp(App);
app.use(router);
app.mount('#app');

// src/views/UserProfile.vue
<template>
  <div>
    <h1>User Profile</h1>
    <p>User ID: {{ id }}</p>
    <button @click="goToHome">Go to Home</button>
    <button @click="goToUser(nextUserId)">Go to User {{ nextUserId }}</button>
  </div>
</template>

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

// When props: true is used in the route definition
// the route params are passed as props to the component.
const props = defineProps({
  id: {
    type: String,
    required: true
  }
});

const router = useRouter();

const nextUserId = computed(() => {
  const currentId = parseInt(props.id, 10);
  return isNaN(currentId) ? 1 : currentId + 1;
});

const goToHome = () => {
  router.push('/'); // Programmatic navigation to home
};

const goToUser = (userId) => {
  router.push({ name: 'UserProfile', params: { id: userId } }); // Programmatic navigation with params
};
</script>
How it works: This code sets up Vue Router 4 with a dynamic route (`/user/:id`) and demonstrates programmatic navigation. The `UserProfile` component receives the `id` parameter as a prop due to `props: true` in the route definition. It uses `useRouter()` to access the router instance and navigate programmatically using `router.push()`, both to a static path and a named route with parameters.

Need help integrating this into your project?

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

Hire DigitalCodeLabs