首頁  >  問答  >  主體

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

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

它現在可以工作,但不是 100% 我希望它的行為。截至目前,當不在/registration 頁面上並單擊時,它會完美滾動到表單,但是當我在/registration 頁面本身並單擊路由器連結時,我會收到警告

嘗試捲動到不在頁面上的元素:未定義

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

網站標頭元件

#
<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);
    }
  }
}

註冊頁面元件

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

P粉627027031P粉627027031241 天前362

全部回覆(2)我來回復

  • P粉633733146

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

    使用 setTimeout:

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

    }

    回覆
    0
  • P粉668146636

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

    首先需要在yarn中加入vue-scrollto,然後在nuxt.config.js中加入以下設定

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

    那麼,這個模板應該可以解決問題

    
    
    sssccc
    

    嘗試從另一個頁面進行此操作,效果很好,也無需從此頁面呼叫vue-scrollto,只需使用簡單的<nuxt-link> 即可移動。


    此文件頁面可以幫助您了解$refs: https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component- Instances-amp-Child-Elements

    #

    回覆
    0
  • 取消回覆