JAVASCRIPT

Programmatic Navigation and Route Parameters in Vue Router

Learn to navigate programmatically and access route parameters in Vue 3 using `useRouter` and `useRoute` from Vue Router for dynamic routing.

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

const routes = [
  { path: '/', name: 'Home', component: Home },
  { path: '/users/:id', name: 'UserDetail', component: UserDetail },
];

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

export default router;

// views/Home.vue
<template>
  <div>
    <h1>Home Page</h1>
    <p>Welcome! Click a user to see their details:</p>
    <ul>
      <li v-for="user in users" :key="user.id">
        <button @click="goToUserDetail(user.id)">
          {{ user.name }}
        </button>
      </li>
    </ul>
    <button @click="goToAboutPage">Go to (Non-existent) About Page</button>
  </div>
</template>

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

const router = useRouter();

const users = ref([
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
]);

const goToUserDetail = (userId) => {
  // Programmatic navigation with route name and params
  router.push({ name: 'UserDetail', params: { id: userId } });
};

const goToAboutPage = () => {
  // Programmatic navigation to a path
  router.push('/about'); // This would navigate to /about
};
</script>

// views/UserDetail.vue
<template>
  <div>
    <h1>User Detail</h1>
    <p v-if="!user">Loading user...</p>
    <div v-else>
      <p>User ID: {{ userId }}</p>
      <p>User Name: {{ user.name }}</p>
      <p>User Email: {{ user.email }}</p>
    </div>
    <button @click="goBack">Go Back</button>
  </div>
</template>

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

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

const userId = ref(null);
const user = ref(null);

const fetchUser = async (id) => {
  user.value = null; // Clear previous user data
  // Simulate API call
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
  const data = await response.json();
  user.value = data;
};

// Watch for changes in route.params.id to re-fetch user data
watchEffect(() => {
  userId.value = route.params.id;
  if (userId.value) {
    fetchUser(userId.value);
  }
});

const goBack = () => {
  router.back(); // Go back to the previous entry in the history stack
};
</script>
How it works: This snippet demonstrates how to perform programmatic navigation and access route parameters using Vue Router's Composition API (`useRouter` and `useRoute`). In `Home.vue`, `router.push()` is used to navigate to a user detail page, passing the `userId` as a route parameter. In `UserDetail.vue`, `useRoute()` allows access to the `route.params.id` to fetch and display specific user data. The `watchEffect` ensures that the user data is re-fetched whenever the `id` parameter in the URL changes, providing a dynamic and responsive user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs