better-scroll实现菜单和列表的双向滑动功能

1.引入

import BScroll from 'better-scroll'

2.使用
html

<template>
   <div class="menu-wrapper" ref="menuWrapper">
   //使用vue 2.0 "ref"属性便于访问和获取dom元素
        <ul>
        <li v-for="(item, index) in goods" class="menu-item" :class="{'current':currentIndex===index}" @click="selectMenu(index)">
        </li>
      </ul>
   </div>

   <div class="foods-wrapper" ref="foodsWrapper">
        <ul>
            <li v-for="item in goods" class="food-list food-list-hook"></li>
        </ul>
   </div>
</template>

js

<script type="text/ecmascript-6">
import BScroll from 'better-scroll'//引入better-scroll
const ERR_OK = 0

export default {
created: function() {
    this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee']

    axios.get('/api/goods')
      .then(response => {
        if (response.data.errno === ERR_OK) {
          this.goods = response.data.data
          //保证dom元素已经渲染
          this.$nextTick(() => {
            //发生更新后要执行的事件
            this._initScroll()
            this._calculateHeight()
          })
        }
      })
  },
methods: {
    selectMenu(index){//实现双向滚动的绑定
      //高版本beter-scroll已经修改了PC短click事件执行两次的bug
      // if(!event._constructed){
      //   return
      // }
      let foodList = this.$refs.foodsWrapper.getElementsByClassName('food-list-hook')
      let el = foodList[index]
      this.foodsScroll.scrollToElement(el,300)
    },
    _initScroll() {
      this.meunScroll = new BScroll(this.$refs.menuWrapper, {
        click:true
      })

      this.foodsScroll = new BScroll(this.$refs.foodsWrapper, {
        probeType: 3
      })
      this.foodsScroll.on('scroll', (pos) => {
        this.scrollY = Math.abs(Math.round(pos.y))
      })
    },
    _calculateHeight() {
      let foodList = this.$refs.foodsWrapper.getElementsByClassName('food-list-hook')
      let height = 0
      this.listHeight.push(height);
      for (let i = 0; i < foodList.length; i++) {
        let item = foodList[i];
        height += item.clientHeight;
        this.listHeight.push(height)
      }
    }
  }
},
data() {
    return {
      goods: [],
      listHeight: [],
      scrollY: 0
    }
  }
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容