1

I have a router link in my site header and when clicked goes to the page /registration which has a form on it. What I would like to achieve is when clicked it scrolls to the reg form using vueScrollTo plugin.

It's working now but not 100% how I would prefer it to behave. As of now when not on the /registration page and clicked it scrolls perfectly to the form however when I am on the /registration page itself and click the router link I get a warning

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

I believe this is happening because I am firing the event on the mounted lifecycle. Is there a better solution to have this work properly?

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>
kissu
  • 40,416
  • 14
  • 65
  • 133
hendy0817
  • 979
  • 2
  • 20
  • 47

2 Answers2

1

You need to firstly yarn add vue-scrollto, then add the following configuration to nuxt.config.js

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

Then, this template should do the trick

<template>
  <div>
    <p ref="regForm" style="background-color: hsl(210, 50%, 13%); height: 50vh; margin-top: 120vh"></p>
  </div>
</template>

<script>
import Vue from 'vue'
import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)

export default {
  mounted() {
    VueScrollTo.scrollTo(this.$refs.regForm, 1000, { easing: 'linear' })
  },
}
</script>

Tried this coming from another page and it is working great, no need to call vue-scrollto from this page neither, move by using a simple <nuxt-link>.


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

tony19
  • 125,647
  • 18
  • 229
  • 307
kissu
  • 40,416
  • 14
  • 65
  • 133
0

With setTimeout:

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

}

Efrén
  • 417
  • 5
  • 7