Search code examples
vue.jsnuxt.jsnuxtjs3

Nuxt3 - NuxtLink to anchor not scrolling on click or page refresh


I'm simply trying to have a page scroll to an anchor point in Nuxt3 and nothing I can do will get it to work. It doesn't scroll on click, or on page refresh with the anchor in the url.

<nuxt-link :to="{path: '/', hash: '#projects'}">Let's go</nuxt-link>

Tried a bunch of other SO answers, adding custom scrollBehaviour code to the nuxtConfig didn't work and trying to install vue-scrollTo in Nuxt3 just gave me this error when running the app with the vue-scrollTo module

ERROR Cannot restart nuxt: serialize is not defined

Any help would be greatly appreciated!

Full code

<script setup>
import '@/assets/css/main.css';

const { data } = await useAsyncData('home', () => queryContent('/').find())
const projects = data

</script>
<template>
  <div>
    <div class="flex flex-col h-screen">
    <div class="lg:p-20 p-10 text-white bg-orange-500">
      <p class="font-playfair lg:text-7xl text-4xl mb-5">Kia Ora, my name is <span class="font-medium italic">George Bates</span></p>
      <p class="font-lato lg:text-3xl text-xl mb-5">Content creator and web developer in Auckland, New Zealand</p>
    </div>
    <div class="lg:p-20 p-10 text-white flex flex-grow" style="background-image: url('images/header.jpg'); background-position: center; background-size: cover;">
    <nuxt-link :to="{path: '/', hash: '#projects'}">Let's go</nuxt-link>
    </div>
    </div>

    <main class="lg:p-20 p-10" id="projects">
      <p class="text-3xl font-playfair mb-5 font-semibold pb-2 text-orange-500">Some of my work</p>
      <Projects :projects="projects" />
    </main>
  </div>
</template>

Solution

  • You said that you already tried to add a custom scrollBehavior, but how did you do that?

    I'm very new to Vue & Nuxt, but thanks to this Github answer, you can customize the scroll behavior, and this works for me:

    File app/route.options.ts:

    import type { RouterConfig } from '@nuxt/schema';
    
    // https://router.vuejs.org/api/#routeroptions
    export default <RouterConfig>{
      scrollBehavior(to, from, savedPosition) {
        return {
          el: to.hash,
          behavior: 'smooth',
        };
      },
    };
    

    (Here I put a smooth behavior, but default seems to be auto)

    And with a sample of code like:

    ...
    <NuxtLink :to="{path: '/', hash: '#anchor'}">Let's go!</NuxtLink>
    ...