在 Vue.js 中,如何滚动到导入的组件?



我知道 Vue 的 scrollBehavior 函数,但我不确定如何在我的代码中使用它。

我有一个索引页面,其中的部分由导入的 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>

但是如果我单击"关于",它只会将我带到"关于"组件的单独页面。 当我单击"关于"时,我希望页面向下滚动到嵌套在我的索引页面上的导入的关于组件。

我怎样才能做到这一点?我需要在路径上改变吗?

您尝试实现的路由器的想法实际上是将"关于组件"视为一个页面,单击它时,它将转到该页面(并更改URL(

所以,为了实现你想要的,我实际上建议使用纯javascript。

首先,给出About组件和 id(如果你更喜欢 Vue ref,则提供 ref 或 ref(

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

然后绑定一个方法点击导航事件

<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

最新更新