JAVASCRIPT

Programmatic Navigation and Custom Scroll Behavior in Vue Router 4

Learn to programmatically navigate between routes and define custom scroll behavior for smooth transitions and anchor linking in Vue Router 4 applications.

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

const routes = [
  { path: '/', component: () => import('../views/Home.vue') },
  { path: '/about', component: () => import('../views/About.vue') },
  { path: '/products/:id', name: 'product-detail', component: () => import('../views/ProductDetail.vue') }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else if (to.hash) {
      return {
        el: to.hash,
        behavior: 'smooth',
        top: 70 // Offset from the top (e.g., for a fixed header)
      };
    } else {
      return { top: 0, behavior: 'smooth' };
    }
  }
});

export default router;

// In a Vue component (e.g., Home.vue):
// <template>
//   <div>
//     <h1>Home Page</h1>
//     <button @click="goToAbout">Go to About</button>
//     <button @click="goToProduct(123)">View Product 123</button>
//     <a href="#section-2">Go to Section 2 (on current page)</a>
//     <div style="height: 1000px;"></div>
//     <h2 id="section-2">Section 2</h2>
//   </div>
// </template>
//
// <script setup>
// import { useRouter } from 'vue-router';
//
// const router = useRouter();
//
// function goToAbout() {
//   router.push('/about');
// }
//
// function goToProduct(id) {
//   router.push({ name: 'product-detail', params: { id } });
// }
// </script>
How it works: This snippet demonstrates configuring custom scroll behavior in Vue Router 4, allowing the page to scroll to the top or to a specific hash anchor with smooth animation, useful for single-page navigation or consistent user experience. It also shows how to use `useRouter` within a component to perform programmatic navigation, pushing new routes onto the history stack by path or by 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