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>