怎么在vue中实现左右联动效果-创新互联
这篇文章给大家介绍怎么在vue中实现左右联动效果,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

首先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)
}关于怎么在vue中实现左右联动效果就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网页标题:怎么在vue中实现左右联动效果-创新互联
浏览路径:http://www.scyingshan.cn/article/didoso.html


咨询
建站咨询
