Vue || How To Set Up Vue Smooth Scroll Behavior With Vue Router Using Vue
The following is a module which demonstrates how to set up smooth anchor scroll behavior when navigating to a new route with Vue using Vue Router.
Note: The examples below assumes your project is already set up and configured. For an overview on how to get started with Vue and Vue Router, visit the official documentation.
1. Router Index File
The example below is a sample router index.js file. This file sets up the routes in the project. Its also where you set up the scrolling behavior when navigating to a new route.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 26, 2020 // Taken From: http://programmingnotes.org/ // File: index.js // Description: Router index.js file // ============================================================================ import { createWebHistory, createRouter } from "vue-router"; const routes = []; const router = createRouter({ history: createWebHistory(), routes, scrollBehavior(to, from, savedPosition) { let defaultPos = {left: 0, top: 0}; if (savedPosition) { return savedPosition; } else if (to.hash) { let elem = document.querySelector(to.hash); return elem ? elem.scrollIntoView({ behavior: 'smooth' }) : defaultPos; } else { return defaultPos; } } }); export default router; // http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply