乐趣区

betterscroll笔记

安装
npm install better-scroll –save
引入
import BScroll from ‘better-scroll’
基础
better-scroll 支持多参数配置,可以在初始化的时候传入第二个参数
let scroll = new BScroll(‘.wrapper’,{

scrollY: true,
click: true

})
这样就实现了一个纵向可点击的滚动效果
参数说明:
scrollY:Boolean
当设置为 true 的时候,可以开启纵向滚动
click:Boolean
better-scroll 默认会阻止浏览器的原生 click 事件。当设置为 true,better-scroll 会派发一个 click 事件,
我们会给派发的 event 参数加一个私有属性_constructed,值为 true。
但是自定义的 click 事件会阻止一些原生组件的行为。
Demo:
实现效果:


滑动右侧左侧对应的类别显示高亮
点击左侧的类别名称右侧滑动到对应的位置
分析:
(1)高亮显示通过 current 类来控制,右侧滑动到不同位置,更新左侧的 current 显示
(2) 即:实时监听 scrollY/ 将右侧每个类的顶部位置记录下来
goods.vue
左侧容器:
<div class=”menu-wrapper” ref=”menuWrapper”>

...

</div>

右侧容器:
<div class=”foods-wrapper” ref=”foodWrapper”>

...

</div>


JS 部分:
data 部分:
data(){

return {// 存放右侧 foodWrapper 容器中,每一个 item(li.food-list-hook)距离顶部的 height
    listHeight:[],
    // 垂直滚动的距离(实时变化的)
    scrolly:0,
    // 商品列表
    goods:[]}

}
初始化部分:
在 created 方法中需要进行,数据的获取,以及左侧 menuWrapper 容器和右侧 foodWrapper 容器的初始化
created(){

// 使用 vue-resource 请求本地数据,模拟后台数据(注意必须放在 static 目录下)this.$http.get("../static/data.json").then(
    response=>{
     // 获取成功之后执行
     response=response.body;
     this.goods=response.goods;
     // 为了避免数据请求没有完成,就执行 foodWrapper 和 foodWrapper 的 scroll 初始化
     // 以及计算 current 高亮位置的方法就已经执行,其调用应在数据获取成功之后执行
     this.$nextTick(()=>{this._initScroll();
         this._calculateHeight()})
     
    },
    error=>{console.log("调用失败"+error)
    }
)

}

methods
_initScroll 初始化,实现滚动
_initScroll(){

// 初始化左侧滚动(滑动类默认是没有点击的,必须加上 click:true 才能触发事件)this.menuScroll=new BScroll(this.$refs.menuWrapper,{click:true})
// 创建右侧的滚动
/*
    probeType:Number 
    默认值 0
    可选值:1、2、3
    作用:有时候我们需要知道滚动的位置。当 probeType 为 1 的时候,会非实时(屏幕滑动超过一定时间后)
    派发 scroll 事件; 当 probeType 为 2 时,会在屏幕滑动的过程中实时的派发 scroll 事件
    当 probeType 为 3 的时候,不仅在屏幕滑动的过程中,而且在 momentum 滚动动画运行过程中实时派发 scroll 事件
*/
this.foodScroll=new BScroll(this.$refs.foodWrapper,{
    probeType:3
    click:true
});
// 为右侧 foodWrapper 绑定 scroll 事件
this.foodScroll.on('scroll',(pos)=>{
    //scrolly 中存放实时滚动的坐标
    this.scrolly=Math.abs(Math.round(pos.y));
})

}
_calculateHeight 计算每一个 item(li.food-list-hook)距离顶部的 height


点击左侧菜单,右侧滚动到对应的位置
selectMenu(index,event){

//index 与 foodWrapper 中每个 li.food-list-hook 的 index 相对应
// 首先去掉 better-scroll 自带的点击事件
if(!event._constructed){return;}
// 获取所有的 li.food-list-hook
let foodList=this.$refs.foodWrapper.getElementsByClassName("food-list-hook");
// 与左侧点击元素的下标相对应的右侧的某个 li.food-list-hook
let el=foodList[index];
// 执行点击后滚动到对应元素的操作
this.foodScroll.scrollToElement(el,300);

}

关于左侧 menu current 高亮位置的计算
computed:{

currentIndex(){for(let i=0;i<this.listHeight.length;i++){let height=this.listHeight[i];
        let height2=this.listHeight[i+1];
        if(!height2||(this.scrolly>height&&this.scrolly<height2)){return i;}
    }
    return 0;

}

}

退出移动版