Vue实战商城项目(八)—— 详情页顶部导航栏跳转


前言

本章概述:滚动内容显示对应标题,点击对应标题跳转到相应位置


一、滚动内容显示对应标题

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的刷新问题做一个优化。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值