
(八)在vue中使用better-scroll,实现内容区域的滚动效果,以及右边与左边内容相对应,左边呈现高亮状态
发布日期:2021-05-08 17:19:57
浏览次数:18
分类:精选文章
本文共 1938 字,大约阅读时间需要 6 分钟。
better-scroll.js 滚动插件使用指南
1. 安装与引入
在项目根目录下安装better-scroll,可以通过npm命令进行:
npm install better-scroll --save
安装完成后,插件会被添加到package.json的dependencies中。
接下来,在需要使用该插件的.vue文件中引入:
import BScroll from 'better-scroll';
2. 实现固定高度滚动
在.goods.vue文件中,设置以下样式:
.goods { position: absolute; top: 174px; bottom: 46px; width: 100%; overflow: hidden;}
确保父容器有固定高度,overflow设置为hidden以限制内容范围。
3. 实现内容滚动
在goods.vue的script部分,初始化better-scroll实例:
export default { data() { return { goods: [] }; }, created() { this.$http.get('/api/goods').then(res => { if (res.errno === ERR_OK) { this.goods = res.data; this.$nextTick(() => { this._initScroll(); }); } }); this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee']; }, methods: { _initScroll() { this.menuScroll = new BScroll(this.$refs.menuWrapper, {}); this.foodsScroll = new BScroll(this.$refs.foodsWrapper, { probeType: 3 }); } }};
4. 实现联动效果
在data中定义:
data() { return { goods: [], listHeight: [], scrollY: 0 };}
计算右侧li的高度并累加:
_calcualteHeight() { let foodList = this.$refs.foodList; let height = 0; this.listHeight.push(height); for (let i = 0; i < foodList.length; i++) { height += foodList[i].clientHeight; this.listHeight.push(height); }}
在_initScroll中添加滚动监听:
this.foodsScroll.on('scroll', pos => { if (pos.y <= 0) { this.scrollY = Math.abs(Math.round(pos.y)); }});
通过计算currentIndex,实现左边高亮:
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;}
在selectMenu中,实现右边滚动到对应位置:
selectMenu(index, event) { if (!event._constructed) return; let foodList = this.$refs.foodList; let el = foodList[index]; this.foodsScroll.scrollToElement(el, 300);}
通过以上方法,可以实现内容的上下滑动和左右联动效果。