簡體   English   中英

Vue滾動以錨定在另一個頁面上?

[英]Vue scroll to anchor on another page?

我的站點標題中有一個路由器鏈接,單擊時轉到頁面/registration ,該頁面上有一個表格。 我想要實現的是,當單擊它時,它會使用vueScrollTo 插件滾動到 reg 表單。

它現在正在工作,但不是 100% 我希望它表現得如何。 截至目前,當不在/registration頁面並單擊它時,它會完美滾動到表單,但是當我在/registration頁面本身並單擊路由器鏈接時,我會收到警告

試圖滾動到不在頁面上的元素:未定義

我相信這種情況正在發生,因為我在已安裝的生命周期中觸發了該事件。 有沒有更好的解決方案可以正常工作?

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>

您需要首先yarn add vue-scrollto ,然后將以下配置添加到nuxt.config.js

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

然后,這個模板應該可以解決問題

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

從另一個頁面嘗試了這個,它工作得很好,也不需要從這個頁面調用vue-scrollto ,使用簡單的<nuxt-link>移動。


該文檔頁面可以幫助您理解$refshttps ://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component-Instances-amp-Child-Elements

使用 setTimeout:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM