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,
    }
    }
    vue better-scroll 实现滚动_第1张图片
  3. 写样式
    a.获取dom结构的父容器内添加ref="foodwrapper"
    b. :class="{'current':currentIndex == index}"
    c. class="food-list good-List-hook"
    vue better-scroll 实现滚动_第2张图片
  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;ilet item = goodsList[i];
    height += item.clientHeight;
    this.listHeight.push(height);
    }
    },
    vue better-scroll 实现滚动_第3张图片
  6. 回调this.initScroller(); this.calculateHeight();事件
    created() {
    this.$nextTick(() =>{
    this.initScroller();
    this.calculateHeight();
    });
    }
    vue better-scroll 实现滚动_第4张图片
  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)
}
vue better-scroll 实现滚动_第5张图片

你可能感兴趣的:(better-scroll)