georgewoofbates
georgewoofbates

Reputation: 330

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>

Upvotes: 1

Views: 2628

Answers (2)

Marcus
Marcus

Reputation: 558

What works for me is even simpler. Just add the following into the nuxt.config.ts file:

  router: {
    options: {
      scrollBehaviorType: "smooth",
    },
  },

And that's all you need.

You can read more from this official Nuxt3 documentation under the title "Scroll Behavior for hash links".

Hope it helps!

Upvotes: 0

thithip
thithip

Reputation: 146

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>
...

Upvotes: 1

Related Questions