继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

vue better-scroll 实现滚动

Lizzy_
关注TA
已关注
手记 2
粉丝 9
获赞 10
  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)
}
图片描述

打开App,阅读手记
4人推荐
发表评论
随时随地看视频慕课网APP