JAVASCRIPT

Vue Router 4 Programmatic Navigation and Route Parameters

Navigate users programmatically in Vue 3 using Vue Router 4. Learn to push routes, pass dynamic parameters, and query strings effectively.

// router/index.js (simplified)
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 }
];

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

export default router;

// components/NavigationComponent.vue
<template>
  <div>
    <button @click="goToHomePage">Go to Home</button>
    <button @click="goToUser(123)">Go to User 123</button>
    <button @click="searchProducts('vue')">Search 'vue'</button>
  </div>
</template>

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

const router = useRouter();

const goToHomePage = () => {
  router.push({ name: 'Home' });
};

const goToUser = (userId) => {
  router.push({ name: 'UserProfile', params: { id: userId } });
};

const searchProducts = (query) => {
  router.push({ path: '/products', query: { q: query, page: 1 } });
};
</script>
How it works: This snippet demonstrates programmatic navigation using Vue Router 4's `useRouter` composable. It shows how to push new routes by name or path, pass dynamic parameters for routes like user IDs, and add query parameters for search functionalities. This is crucial for navigating users based on application logic rather than direct link clicks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs