当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue中实现左右联动的效果

vue中实现左右联动的效果

2018年08月06日  | 移动技术网IT编程  | 我要评论

ca1196,磁力泵型号,不知火舞轮x聚会

这里的坑还是蛮多的,花了一个多小时,才理清楚。

 做一下笔记,以便于复习。

首先呢,需要让左右的布局都可以滚动,这里使用了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中实现左右联动的效果,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网