javascript - 在 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)
<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
改为使用;