Skip to content

"No lenis instance found" by useLenis in router.options.ts in Nuxt #473

@florian-strasser

Description

@florian-strasser

I really love lenis and actually everything "works", but I get a warning since I use useLenis within my router.options.ts to enable scrolling again when the page transition is finished.

No lenis instance found, either mount a root lenis instance or wrap your component in a lenis provider

I need this for the scenario where I navigate from the menu that expands and therefore the scroll disabled.

You can replicate this by wrapping a VueLenis Component around the NuxtPage Component and add this code for /app/router.options.ts

import type { RouterConfig } from "@nuxt/schema";
import { useLenis } from "lenis/vue";

export default <RouterConfig>{
  scrollBehavior(to, from, savedPosition) {
    const nuxtApp = useNuxtApp();
    const lenis = useLenis();
    if (savedPosition) {
      if (to.path == from.path) return savedPosition;
      else
        return new Promise((resolve) => {
          if (lenis.value) lenis.value.stop();
          nuxtApp.hooks.hookOnce("page:transition:finish", () => {
            requestAnimationFrame(() => {
              resolve(savedPosition);
              lenis.value.start();
            });
          });
        });
    } else {
      if (to.hash && to.path == from.path) {
        return { el: to.hash };
      } else if (to.hash && to.path != from.path) {
        return new Promise((resolve) => {
          if (lenis.value) lenis.value.stop();
          nuxtApp.hooks.hookOnce("page:transition:finish", () => {
            requestAnimationFrame(() => {
              resolve({ el: to.hash });
              lenis.value.start();
            });
          });
        });
      } else {
        if (to) {
          return new Promise((resolve) => {
            if (lenis.value) lenis.value.stop();
            nuxtApp.hooks.hookOnce("page:transition:finish", () => {
              requestAnimationFrame(() => {
                resolve({ top: 0, left: 0 });
                lenis.value.start();
              });
            });
          });
        } else {
          return { top: 0, left: 0 };
        }
      }
    }
  },
};

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