vue导航栏根据页面滚动变化,点击导航栏滚动页面

以下是两个导航栏按钮对应两个div。可以自己修改.我是参考 ==》博客《=== 的

这里是在computed下监听导航栏的点击事件,this.$refs = undefined。

1、可以在this.$nextTick(()=>{ //do something})中执行滚动事件

    computed:{
     ...mapState('menu', {
          navActive: 'navActive'
     }),
     childrenActive(){
        if (this.navActive>-1&&this.achieveMenu){
          this.$nextTick(()=>{
             this.handleLeft(this.navActive)
           })
        }
        return this.navActive;
      },
  },

2、也可以在mouted()中将一个变量设置为_isMouted = true,在computed()中监听

computed:{
     ...mapState('menu', {
          navActive: 'navActive'
     }),
     childrenActive(){
        if (this.navActive>-1&&this.achieveMenu){
          if (this._isMounted){
            this.handleLeft(this.navActive)
          }
        }
        return this.navActive;
      },
},
mouted(){
    this._isMounte = true;
},

 

 

1、点击导航栏,使页面滚动到顶部

// 点击导航菜单,div滚动到父元素的顶部
//(这个函数是通过computed监听navActive属性的变化执行的)
    handleLeft(index) {
      if(index == ACHIEVE_CONFIG.TEXT1){
         //使ref = "texstName"的div 滑到顶部
          this.$refs.texstName1.scrollIntoView({
            behavior: "smooth", 
            block:"start"  
          });
        
        }

      if(index == ACHIEVE_CONFIG.TEXT2){
         //使ref = "texstName"的div 滑到顶部
          this.$refs.texstName2.scrollIntoView({
            behavior: "smooth",  // 平滑过渡
            block: "start"  // 上边框与视窗顶部平齐。默认值
          });
         
        }
   
      this.scrollState=false;//全局变量,是滚动事件延迟触发

      let timeId;
      clearTimeout(timeId);
      timeId = setTimeout(() => {
        this.scrollState=true;
      },200);
    },


    

2、滚动页面,使对应的导航栏高亮

// 监听页面元素滚动,改变导航栏选中
    scrollToTop() {
      // 页面滚动停止100毫秒后才会执行下面的函数。
      clearTimeout(this.timeId);
          this.timeId = setTimeout(() => {
            if (!that.scrollState) {
              return;
            }
            if (that.$refs.testName1.getBoundingClientRect().top<=300){//距离页面顶部300范围内,菜单栏是active状态
              this.navActiveMutations(ACHIEVE_CONFIG.TEXT1);//使用vuex保存导航栏选中的序号,因为我的导航栏和滚动的页面是不同的.vue文件。ACHIEVE_CONFIG.TEXT是我定义的导航栏的序号
            }
            if (that.$refs.testName2.getBoundingClientRect().top<=300){
              this.navActiveMutations(ACHIEVE_CONFIG.TEXT2);
            }
            
            // console.log('执行完了哦');
          }, 100);
    },

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值