Skip to content

In Nuxt navigating to a new page doesn't start at the top when the previous page didn't finish scrolling #498

@twnty-dev

Description

@twnty-dev

Hi, I have the same issue as here #373 (comment), but in Nuxt.

Versions:
"lenis": "^1.3.17"
"nuxt": "4.1.2"

My config:

// app.vue

<template>
  <NuxtLoadingIndicator color="#0A84FF" :throttle="100" :height="4" />
  <VueLenis
    root
    :options="{
      lerp: 0.2,
      wheelMultiplier: 0.7,
      gestureOrientation: 'vertical',
      normalizeWheel: false,
      smoothTouch: false,
    }" />
  <NuxtLayout>
    <NuxtPage/>
  </NuxtLayout>
</template>


// router.options.ts

import type { RouterOptions } from "@nuxt/schema";
import { useNuxtApp } from "#app";

export default (<RouterOptions>{
  scrollBehavior(to, from, savedPosition) {
    if (!!to.hash) return;

    const isPagination = to.query.page !== from.query.page;
    if (to.path === from.path && isPagination) {
      return {
        top: 0,
        behavior: "smooth",
      };
    }
    if (to.path === from.path && !isPagination) {
      return;
    }
    /**
     * IMPORTANT:
     *
     * This solutions is related to the default SEO URL pattern structure:
     * {{ product.translated.name }}/{{ product.productNumber }}
     *
     * For more information please visit:
     * https://docs.shopware.com/en/shopware-6-en/settings/seo
     *
     * ----------------------------------------------
     *
     * Do not scroll to top when switching between product variants
     *
     * Assumptions:
     * - product with variants contains minimum 2 subdirectories
     * - for the same product 1 subdirectory is the same
     */

    // if (from.params?.all?.length > 1 && to.params?.all?.length > 1 && from.params?.all[0] === to.params?.all[0]) {
    //   return null;
    // }
    //

    if (savedPosition) return savedPosition;

    if (to.path === "/app" || to.path === "/") {
      return {
        top: 0,
        behavior: "auto",
      };
    }

    const nuxtApp = useNuxtApp();

    // Wait until the page navigation (and its transition) has finished
    // before scrolling to the top to avoid an immediate jump.
    return new Promise((resolve) => {
      nuxtApp.hooks.hookOnce("page:finish", async () => {
        await nextTick();

        resolve({
          top: 0,
          behavior: "smooth",
        });
      });
    });
  },
});

Maybe you have some advices how to deal with this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions