前言
本章概述:滚动内容显示对应标题,点击对应标题跳转到相应位置
一、滚动内容显示对应标题
1.获取对应组件的offsetTop
getThemeTops(){
this.themeTopsY = [] //创建一个数组存放各个节点的offsetTop
this.themeTopsY.push(0); //商品
this.themeTopsY.push(this.$refs.params.$el.offsetTop); //参数
//评论区分两种情况,有评论和无评论
if(this.$refs.comment.$el.offsetTop){
this.themeTopsY.push(this.$refs.comment.$el.offsetTop);
}else {
this.themeTopsY.push((this.$refs.goods.$el.offsetTop - 150));
}
//推荐
this.themeTopsY.push((this.$refs.goods.$el.offsetTop - 50));
this.themeTopsY.push(Number.MAX_VALUE);
}
2.获取滚动条的position
因为better-scroll之前我们已经封装好了,只需要直接传入相应的参数即可获取到postion。
<Scroll class="content" ref="scroll" :probe-type="3" @scroll="contentScroll">
同样我们这里需要解决一下之前提到过得better-scroll不能滚动的问题,如果还不知道怎么解决,可参考之前的文章:Vue商城项目开发要点笔记(四)—— better-scroll
3.判断当前滚动条位置是否对应标题
在data中定义一个currentIndex,通过判断postion和offsetTop的位置改变currentIndex,并改变导航组件中currentIndex的值
contentScroll(position){
this.isShowBackTop = (-position.y) > 1000
const positionY = -position.y
let length = this.themeTopsY.length
for (let i = 0 ; i < length - 1; i++){
if( this.currentIndex !== i && (positionY >= this.themeTopsY[i] && positionY < this.themeTopsY[i + 1]) ) {
this.currentIndex = i;
this.$refs.navBar.currentIndex = i
}
}
}
在导航栏子组件绑定一个动态样式
<div v-for="(item,index) in titles"
:key="item.index"
:class="{active: index === currentIndex}"
//激活状态通过判断当前索引是否等于currentIndex
@click="titleClick(index)">
二、点击对应标题跳转到相应位置
因为前面我们获取到对应组件的位置了,所以这一步很简单,只需要给导航栏绑定点击事件将index值传给父组件,父组件利用better-scroll自带的跳转方法将滚动条跳转到相应位置即可
titleClick(index){
this.currentIndex = index //点击后对应项显示激活
this.$emit('titleClick',index)
}
子组件将index值传给父组件,父组件更具index跳转到对应位置
代码如下(示例):
展示如下:
总结
以上便是vue中better-scroll 导航栏跳转的具体内容。需要注意的点是better-scroll的无法滚动的问题一定要解决,不然跳转可能不是预期的位置,原因之前也解释过了,图片没有加载完整。之后讲到防抖函数可对better-scroll的刷新问题做一个优化。