scrollroutesanchornuxt3.js

Nuxt 3 Smooth Scrolling with Hash Links


In my Nuxt.js 3 project, I want to implement single-page navigation. And I followed following articles but it didn't work. any suggestions?


Solution

  • The correct way to do it in Nuxt.js 3 is to create the "router.scrollBehaviour.js" file in the plugins/ directory. Its content should be

    import { defineNuxtPlugin } from "#app";
    
    export default defineNuxtPlugin((nuxtApp) => {
      nuxtApp.$router.options.scrollBehavior = async (to, from, savedPosition) => {
        if (savedPosition) {
          return savedPosition;
        }
    
        const findEl = async (hash, x = 0) => {
          return (
            document.querySelector(hash) ||
            new Promise((resolve) => {
              if (x > 0) {
                return resolve(document.querySelector("#app"));
              }
              setTimeout(() => {
                resolve(findEl(hash, 1));
              }, 300);
            })
          );
        };
    
        if (to.hash) {
          const el = await findEl(to.hash);
    
          if ("scrollBehavior" in document.documentElement.style) {
            console.log("hash path hit scroll to");
            return window.scrollTo({ top: el.offsetTop, behavior: "smooth" });
          } else {
            return window.scrollTo(0, el.offsetTop);
          }
        }
        return { left: 0, top: 0, behaviour: "smooth" };
      };
    })