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

首先呢,需要讓左右的布局都可以滾動,這里使用了betterScroll
npm i better-scroll
import BScroll from 'better-scroll'
methods: {
_initScroll () {
this.menuScroll = new BScroll((this.$refs.menu), {
click: true
因為betterscroll默認會阻止點擊事件。這里要設(shè)置一下
})
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。
總結(jié)
以上所述是小編給大家介紹的vue中實現(xiàn)左右聯(lián)動的效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
vue3接口數(shù)據(jù)賦值對象,渲染報錯問題及解決
這篇文章主要介紹了vue3接口數(shù)據(jù)賦值對象,渲染報錯問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
基于vue2.0的活動倒計時組件countdown(附源碼下載)
這是一款基于vue2.0的活動倒計時組件,可以使用服務(wù)端時間作為當前時間,在倒計時開始和結(jié)束時可以自定義回調(diào)函數(shù)。這篇文章主要介紹了基于vue2.0的活動倒計時組件countdown,需要的朋友可以參考下2018-10-10
Element-ui el-tree新增和刪除節(jié)點后如何刷新tree的實例
這篇文章主要介紹了Element-ui el-tree新增和刪除節(jié)點后如何刷新tree的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08

