vue better-scroll 实现滚动

  字号
  1. npm下载 better-scroll插件
    npm install better-scroll --save
    引入import BScroll from 'better-scroll'

  2. 定义data 变量
    data() {
    return {
    goods:[],
    listHeight:[],
    scrollY:0,
    }
    }
    图片描述
  3. 写样式
    a.获取dom结构的父容器内添加ref="foodwrapper"
    b. :class="{'current':currentIndex == index}"
    c. class="food-list good-List-hook"
    图片描述
  4. 用this.$refs.menuwrapper获取到dom。
    initScroller() {
    this.menuScroll = new BScroll(this.$refs.menuWrapper, {
    click:true
    });
    this.foodsScroll = new BScroll(this.$refs.foodsWrapper,{
    probeType:3 ,
    click:true
    });
    this.foodsScroll.on('scroll', (pos) => {
    this.scrollY = Math.abs(Math.round(pos.y)) ;
    })
    },
  5. 组装高度 listHeight:[],
    calculateHeight(){
    let goodsList =this.$refs.foodsWrapper.getElementsByClassName('good-List-hook');
    let height = 0;
    this.listHeight.push(height);
    for(let i=0;i<goodsList.length;i++){
    let item = goodsList[i];
    height += item.clientHeight;
    this.listHeight.push(height);
    }
    },
    图片描述
  6. 回调this.initScroller(); this.calculateHeight();事件
    created() {
    this.$nextTick(() =>{
    this.initScroller();
    this.calculateHeight();
    });
    }
    图片描述
  7. 计算高度listHeight 的当前值currentIndex
    computed:{
    currentIndex(){
    for(let i = 0; i < this.listHeight.length; i++){
    let height1 = this.listHeight[i];
    let height2 = this.listHeight[i + 1];
    if( !height2 || (this.scrollY >= height1&&this.scrollY < height2)){
    return i;
    }
    }
    return 0;
    }
    }
  8. 点击事件高亮
    selectMenu(index,event){
    if(!event._constructed){
    return;
    }
    let goodsList = this.$refs.foodsWrapper.getElementsByClassName('good-List-hook');
    let el = goodsList[index];
    this.foodsScroll.scrollToElement(el,300);
    },

7.如果报错可能是要加上
scrollToElement() {
this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments)
}
图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值