Vue bettr-scroll 滚动

1.npm下载 better-scroll插件

npm install better-scroll --save
引入import BScroll from 'better-scroll'

2.定义data 变量

data() {
return {
goods:[],
listHeight:[],
scrollY:0,
}
}

![image](https://upload-images.jianshu.io/upload_images/25150671-5d0d2c5cbe40ece3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

3.写样式

a.获取dom结构的父容器内添加ref="foodwrapper"
b. :class="{'current':currentIndex == index}"
c. class="food-list good-List-hook"
![image](https://upload-images.jianshu.io/upload_images/25150671-f67a0868ca564c9d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

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);
}
},
![image](https://upload-images.jianshu.io/upload_images/25150671-b0f9be4760a48ed6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

6.回调this.initScroller(); this.calculateHeight();事件

created() {
this.$nextTick(() =>{
this.initScroller();
this.calculateHeight();
});
}
![image](https://upload-images.jianshu.io/upload_images/25150671-e4c9efd658e57cbb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

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);
},

9.如果报错可能是要加上

scrollToElement() {
this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments)
}
![image](https://upload-images.jianshu.io/upload_images/25150671-abb3eb5cee840ff5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

转载自https://www.imooc.com/article/31673。

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容