JAVASCRIPT

Programmatic Navigation and Route Parameters with Vue Router

Discover how to programmatically navigate in Vue 3 applications using Vue Router's `useRouter` and `push` method, including passing route parameters and query strings.

// router/index.js (basic setup example)
// import { createRouter, createWebHistory } from 'vue-router';
// import HomeView from '../views/HomeView.vue';
// import ProductDetail from '../views/ProductDetail.vue';
//
// const routes = [
//   { path: '/', name: 'home', component: HomeView },
//   { path: '/products/:id', name: 'product-detail', component: ProductDetail }
// ];
//
// const router = createRouter({
//   history: createWebHistory(),
//   routes
// });
//
// export default router;

// components/NavigationComponent.vue
// <template>
//   <button @click="goToHomePage">Go to Home</button>
//   <button @click="viewProduct(123)">View Product 123</button>
//   <button @click="searchProducts('electronics')">Search Electronics</button>
// </template>
//
// <script setup>
// import { useRouter } from 'vue-router';
//
// const router = useRouter();
//
// function goToHomePage() {
//   router.push({ name: 'home' });
// }
//
// function viewProduct(productId) {
//   router.push({ name: 'product-detail', params: { id: productId } });
// }
//
// function searchProducts(category) {
//   router.push({
//     path: '/products', // Or a named route if you have one for search
//     query: { category: category, sort: 'price_asc' }
//   });
// }
//
// // Example: Replace current route instead of pushing
// function replaceCurrentRoute() {
//   router.replace({ path: '/new-path' });
// }
//
// // Example: Go back in history
// function goBack() {
//   router.back(); // Same as window.history.back()
// }
// </script>
How it works: This snippet demonstrates how to programmatically navigate within a Vue 3 application using the Vue Router's Composition API. By importing `useRouter`, you gain access to the router instance, allowing you to use methods like `router.push()` to navigate to specific routes. It shows how to pass dynamic `params` for route segments and include `query` parameters for filtering or sorting. `router.push()` adds a new entry to the browser's history, while `router.replace()` replaces the current entry, and `router.back()` allows navigating backwards.

Need help integrating this into your project?

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

Hire DigitalCodeLabs