Home  >  Q&A  >  body text

Vue scroll anchor on another page?

I have a router link in the title of my site that when clicked takes me to page /registration which has a form on it. What I want to achieve is that when clicked it scrolls to the registration form using the vueScrollTo plugin.

It works now, but not 100% how I want it to behave. As of now, when not on the /registration page and clicking, it scrolls to the form perfectly, but when I'm on the /registration page itself and click on the router link, I get Got warning

Attempt to scroll to an element that is not on the page: undefined

I believe this is happening because I'm triggering the event during the installed lifecycle. Is there a better solution to make it work?

Site header component

<template>
  <router-link to="/registration"
    class="nav-row--primary__button"
    @click.native="scrollToRegForm()"
  >
    Sign up
  </router-link>
</template>

<script>
export default {
  mounted() {
    if (window.location.href.indexOf("/registration") > 0) {
      const regForm = document.getElementById("regForm");
      setTimeout(() => this.scrollToRegForm(regForm), 1);
    }
  },
  methods: {
    scrollToRegForm(element) {
      VueScrollTo.scrollTo(element, 1000);
    }
  }
}

Registration page component

<div class="container--content spacing-ie" id="regForm">
  <RegistrationForm />
</div>

P粉627027031P粉627027031241 days ago360

reply all(2)I'll reply

  • P粉633733146

    P粉6337331462024-02-22 09:26:00

    Use setTimeout:

    methods: {
    scrollToRegForm(element) {
      this.$router.push('/regForm')
      setTimeout(() =>{
        VueScrollTo.scrollTo(element, 1000);
      }, 1000)
    }

    }

    reply
    0
  • P粉668146636

    P粉6681466362024-02-22 00:07:21

    First you need to add vue-scrollto in yarn, and then add the following configuration in nuxt.config.js

    {
      modules: [
        'vue-scrollto/nuxt',
      ]
    }
    

    Then, this template should solve the problem

    
    
    sssccc
    

    Tried doing this from another page, worked great, no need to call vue-scrollto from this page, just use a simple <nuxt-link> move.


    This documentation page can help you understand $refs: https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component- Instances-amp-Child-Elements

    reply
    0
  • Cancelreply