better-scroll實(shí)現(xiàn)菜單和列表的雙向滑動(dòng)功能

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元素已經(jīng)渲染
          this.$nextTick(() => {
            //發(fā)生更新后要執(zhí)行的事件
            this._initScroll()
            this._calculateHeight()
          })
        }
      })
  },
methods: {
    selectMenu(index){//實(shí)現(xiàn)雙向滾動(dòng)的綁定
      //高版本beter-scroll已經(jīng)修改了PC短click事件執(zhí)行兩次的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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容