簡體   English   中英

在 Vue.js 中,如何滾動到導入的組件?

[英]In Vue.js, how do I scroll to an imported component?

我知道 Vue 的 scrollBehavior function,但我不確定如何在我的代碼中使用它。

我有一個索引頁面,其中部分由導入的 vue 組件組成。 例如

<template>
  <div class="Container">
   <About />
   <Services />
   <Contact />
  </div>
</template>

我的導航欄有所有這些組件的鏈接。

    <template>
    <nav>
    <img class="nav__logo" :src="navLogo" height="40px" width="auto">
        <ul class="nav__row" ref="nav">
            <div class="nav__row__dropdown-toggle-btn" @click="toggleNav">
                <img :src="navMenuIcon" height="40px" width="auto">
            </div>
            <li class="nav__list-item" v-for="(link, index) in navLinks" :key="index"
                @mouseover="hover = true"
                @mouseleave="hover = false"
                :class=" { active: hover } ">
                <router-link :to="link.path">
                    {{ link.text }}
                </router-link>
            </li>
        </ul>
    </nav>
</template>

它從我的 App.vue 腳本中獲取

    <script>
import Navbar from '@/components/Navbar'
import Footer from '@/components/Footer'
export default {
  components: {
    Navbar,
    Footer
  },
  data: () => ({
    navLinks: [
      {
        text: 'Home',
        path: '/'
      },
      {
        text: 'About',
        path: '/about'
      },
      {
        text: 'Contact',
        path: '/contact'
      },
      {
        text: 'Services',
        path: '/services'
      }
    ]
  })
}
</script>

但如果我點擊“關於”,它只會將我帶到“關於”組件的單獨頁面。 當我單擊“關於”時,我希望頁面向下滾動到嵌套在我的索引頁面上的導入的關於組件。

我怎樣才能做到這一點? 我需要在路徑中更改嗎?

您嘗試實現的路由器的想法實際上是將關於組件視為一個頁面,當單擊它時,它將 go 到該頁面(並更改 URL)

所以,為了實現你想要的,我實際上建議使用純 javascript

首先,提供About組件和 id(如果您更喜歡 Vue ref,則提供 ref)

 <template>
      <div class="Container">
       <About id="about"/>
       <Services />
       <Contact />
      </div>
    </template>

然后綁定一個方法來點擊nav的事件

 <li class="nav__list-item" v-for="(link, index) in navLinks" :key="index"
                @mouseover="hover = true"
                @mouseleave="hover = false"
                :class=" { active: hover } ">
                @click=nav(link)
            </li>


data: () => ({
    navLinks: [
      {
        text: 'About',
        id: 'about'
      }
    ]
  }),

methods:{
  nav(link) {
          const position = document.getElementById(link.id).offsetTop;
          // smooth scroll
          window.scrollTo({ top: position, behavior: "smooth" });  
   }
}

如果您更喜歡 Vue ref,可以將所有 id 更改為 ref。 並使用this.$refs[link.id].$el.offsetTop代替;

我發現這個視頻非常有用,我的目標是能夠在同一頁面的組件之間滾動。 但我認為你仍然可以在任何地方申請

https://laracasts.com/series/practical-vue-components/episodes/1

暫無
暫無

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

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