vue中實現(xiàn)左右聯(lián)動的效果
這里的坑還是蠻多的,花了一個多小時,才理清楚。
做一下筆記,以便于復習。

首先呢,需要讓左右的布局都可以滾動,這里使用了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()
})
})
},
這里的代碼一定要在獲取數(shù)據(jù)里面寫nextTick()回調(diào)里面寫代碼,因為需要等待數(shù)據(jù)萬泉加載再去初始化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到一個數(shù)組里面。
this.foodScroll.on('scroll', (pos) => {
this.scrollY = Math.abs(Math.round(pos.y))
})
獲取滾動的值,賦值給scrollY。
然后根據(jù)scrollY 和listHeight的高度區(qū)間做對比,拿到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}"
最后一步是如何實現(xiàn)點擊的時候去讓右邊的滾動到指定的位置。
handleGoodsItem (index) {
let goodEle = this.$refs.good
let foodList = goodEle.getElementsByClassName('goodsItemHook')
let el = foodList[index]
this.foodScroll.scrollToElement(el, 300)
}
這里調(diào)用了scroll的方法:scrollToElement。
總結
以上所述是小編給大家介紹的vue中實現(xiàn)左右聯(lián)動的效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
Vue.js實現(xiàn)按鈕的動態(tài)綁定效果及實現(xiàn)代碼
本文通過實例代碼給大家介紹了Vue.js實現(xiàn)按鈕的動態(tài)綁定效果,代碼簡單易懂,非常不錯,具有參考借鑒價值,需要的的朋友參考下吧2017-08-08
vue 監(jiān)聽鍵盤回車事件詳解 @keyup.enter || @keyup.enter.native
今天小編就為大家分享一篇vue 監(jiān)聽鍵盤回車事件詳解 @keyup.enter || @keyup.enter.native,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Vue3+Vite+TS使用elementPlus時踩的坑及解決
這篇文章主要介紹了Vue3+Vite+TS使用elementPlus時踩的坑及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

