javascriptvue.jsnuxt.jsscrollto

Nuxt.js scrollTo id onclick


So im building a nuxt application, and I want to the Page to scroll down to a specific element, after I clicked a button. The button and the element are in two different components, but on the same Page.

So I read that this is a problem in Nuxt.js and you have to create a specific file to make it work.

I created the folder called app and in app I created the file router.scrollBehavior.js the code of the file it the following

export default async function (to, from, savedPosition) { 
    if (savedPosition) {
      return savedPosition
    }
  
    const findEl = (hash, x) => {
      return document.querySelector(hash) ||
        new Promise((resolve, reject) => {
          if (x > 50) {
            return resolve()
          }
          setTimeout(() => { resolve(findEl(hash, ++x || 1)) }, 100)
        })
    }
  
    if (to.hash) {
      const el = await findEl(to.hash)
      if ('scrollBehavior' in document.documentElement.style) {
        return window.scrollTo({ top: el.offsetTop, behavior: 'smooth' })
      } else {
        return window.scrollTo(0, el.offsetTop)
      }
    }
  
    return { x: 0, y: 0 }
  }

My button is in the hero file, i created a click function called goto()

<template>
  <section class="hero-section">
      <div class="left">
          <header id="hero-text" class="hero-header">
            <h1 @click="goto()">Web Development <br> Web Design</h1>
            <p>Hi, ich bin Alex. Ich designe und programmiere moderne, kreative und schnelle Webseiten. Umgesetzt mit den neusten Technologien.</p>
          </header>

        <UiButtonApp
          id="hero-btn"
          text="Schau dir meine Arbeit an!"
        />
      </div>
      <div class="right">
          <img id="hero-img" src="~/assets/img/hero-img.jpg" alt="hero-img">
          <div id="hero-object"></div>
          <img class="dots" id="hero-dots" src="~/assets/img/dots.png" alt="logo">
      </div>
  </section>
</template>

<script>
import { gsap } from "gsap";

export default {
    data(){
        return{

        }
    },
    methods: {
        goto() {
         //what code to put here
            
        }
    }

    }

How can I now call the function? And make it work?


Solution

  • If you want to use router.scrollBehavior.js. Set a router action and send it to a especific hash:

    methods: {
        goto() {
            this.$router.replace({ name: this.$route.name, hash: '#example' });          
        }
    }
    

    Don`t forget to set id in the component to go.

    <div id="example">
    </div>