仅简单实现大致效果,详细参考:
超详细Vue实现导航栏绑定内容锚点+滚动动画+vue-router(hash模式可用)
效果:
导航条:
<!-- 导航条 -->
<ul class="navs" :class="navBarFixed == true ? 'navBoxactive' : 'navs'">
<a
href="javascript:void(0)"
v-for="(item, index) in yearList"
:key="index"
@click="goAnchor('year' + item.name)"
>{{ item.name }}</a
>
</ul>
列表:
<ul class="newList">
<div
v-for="(item, index) in yearList"
:key="index + 's'"
:id="'year' + item.name"
>
// 标题年份
<div class="yearname">{{ item.name }}</div>
<div
v-for="(item1, index1) in allArticle"
:key="index1"
>
// 内部样式自行定义
<li v-for="(item2, index2) in item1" :key="index2">
<div class="time fl">
<p>{{ dayjs(item2.publishDate).format("M月") }}</p>
</div>
<div class="decoration fl">
<p class="line"></p>
<p class="row">_</p>
</div>
<div class="inner fr">
<h3 class="single-line">{{ item2.title }}</h3>
</div>
</li>
</div>
</div>
</ul>
data:
data() {
return {
navBarFixed: false, //导航吸顶
yearList: [],
allArticle: [],
}
},
mounted() {
// 监听滚动事件
window.addEventListener("scroll", this.scrollnav);
},
destroy() {
// 必须移除监听器,若该vue组件被销毁了,监听器还在会出错
window.removeEventListener('scroll', this.scrollnav)
},
methods: {
// 吸顶
scrollnav() {
// 滚动距离
var scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
// 容器高度
var offsetTop = 610.34;
// 当滚动超过 offsetTop 时,实现吸顶效果
if (scrollTop > offsetTop) {
this.navBarFixed = true;
} else {
this.navBarFixed = false;
}
},
// 导航滑动
goAnchor(selector) {
document.querySelector(`#${selector}`).scrollIntoView({
behavior: "smooth",
});
}
}
样式:
// 导航条吸顶原样式
.navs {
position: absolute;
text-align: center;
width: 80px;
padding: 10px 0;
background-color: rgb(244, 246, 246);
}
// 导航条滚动过程中固定在页面
.navBoxactive {
position: fixed;
top: 20px;
}