这里的坑还是蛮多的,花了一个多小时,才理清楚。
做一下笔记,以便于复习。
首先呢,需要让左右的布局都可以滚动,这里使用了betterScroll
npm i better-scroll import BScroll from 'better-scroll' methods: { _initScroll () { this.menuScroll = new BScroll((this.$refs.menu), { click: true 因为betterscroll默认会阻止点击事件。这里要设置一下 }) this.foodScroll = new BScroll((this.$refs.good), { probeType: 3 用来获取滚动的距离 }) this.foodScroll.on('scroll', (pos) => { this.scrollY = Math.abs(Math.round(pos.y)) }) },
重点:
created () { this.$ajax.get('/api/data.json').then((res) => { this.goods = res.data.goods this.$nextTick(() => { this._initScroll() this.getGoodsHeight() }) }) },
这里的代码一定要在获取数据里面写nextTick()回调里面写代码,因为需要等待数据万泉加载再去初始化scroll和获取右边每一个盒子的高度。
说道高度,高度如何获取呢?
getGoodsHeight () { let goodEle = this.$refs.good let height = 0 this.listHeight.push(height) let foodList = goodEle.getElementsByClassName('goodsItemHook') for (let i = 0; i < foodList.length; i++) { let item = foodList[i] height += item.clientHeight this.listHeight.push(height) } },
这里是获取到每一个盒子的clientHeight的高度进行叠加,在push到一个数组里面。
this.foodScroll.on('scroll', (pos) => { this.scrollY = Math.abs(Math.round(pos.y)) })
获取滚动的值,赋值给scrollY。
然后根据scrollY 和listHeight的高度区间做对比,拿到index:
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 < height2 && this.scrollY >= height1)) { return i } } }
这时候滚动就能获取index的值了,然后给左边的元素去添加active的样式就方便了。
:class="{'active': currentIndex == index}"
最后一步是如何实现点击的时候去让右边的滚动到指定的位置。
handleGoodsItem (index) { let goodEle = this.$refs.good let foodList = goodEle.getElementsByClassName('goodsItemHook') let el = foodList[index] this.foodScroll.scrollToElement(el, 300) }
这里调用了scroll的方法:scrollToElement。
总结
以上所述是小编给大家介绍的vue中实现左右联动的效果,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月25日
2024年09月25日
- 杨千嬅.2002-万紫千红演唱会2CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郭采洁.2015-Begin.Again爱造飞鸡【华纳】【FLAC分轨】
- 许志安.2011-ON.AND.ON【东亚】【WAV+CUE】
- 潘秀琼.1994-木兰从军【名将】【WAV+CUE】
- 纯音入心系列纯音乐《古筝系列-当流行乐遇到古筝》1CD[MP3][1.9GB]
- 纯音入心系列纯音乐《精选古筝名曲100首》1CD[MP3][388.7MB]
- 纯音入心系列纯音乐《天籁古筝》1CD[MP3][331MB]
- 男女对唱典藏天碟《发烧对唱·那个季节里的歌DSD》10CD[WAV]
- 群星2010-歌林精选辑[歌林][WAV+CUE]
- TrioZimbalist-PianoTriosofWeinberg,Auerbach,Dvorak(2024)[24-44,1]wav
- 群星.1992-滚石第一流台湾歌·12王牌大车拼【滚石】【WAV+CUE】
- 林子祥.1984-创作歌集【华纳】【WAV+CUE】
- 周汤豪.2010-周汤豪【华纳】【FLAC分轨】
- Mozart-TheStringQuintets-AmadeusQuartet,CecilAronowitz(2017)[24-44,1][WAV+CUE]
- JamesWilliamsDennisIrwin-Focus(2024,Red)[24-48]FLAC