Vue scroll anchor on another page?
P粉627027031
P粉627027031 2024-02-21 10:17:16
0
2
367

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粉627027031
P粉627027031

reply all(2)
P粉633733146

Use setTimeout:

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

}

P粉668146636

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!