一、better-scroll的使用
1、安装
npm install better-scroll -S
2、使用
<template>
<div class="goods">
<div class="menu-wrapper" ref="menuWrapper">
<ul>
<li v-for="(item,index) in goods" :key="index" class="menu-item">
<span class="text border-1px">
<span v-show="item.type>0" class="icon" :class="classMap[item.type]"></span>
{{item.name}}
</span>
</li>
</ul>
</div>
<div class="foods-wrapper" ref="foodsWrapper">
<ul>
<li v-for="(item,index) in goods" :key="index" class="food-list">
<h1 class="title">{{item.name}}</h1>
<div class="icon">
<img :src="item.icon" alt />
</div>
<div class="content">
<h2 class="name">{{item.name}}</h2>
<p class="desc">{{item.description}}</p>
<div class="extra">
<span class="count">月售{{item.sellCount}}份</span>
<span>好评率{{item.rating}}%</span>
</div>
<div class="price">
<span class="now">¥{{item.price}}</span>
<span v-show="item.oldPrice" class="old">¥{{item.oldPrice}}</span>
</div>
</div>
</li>
</ul>
</div>
</div>
</template>
<script>
import BScroll from "better-scroll";
const ERR_OK = 0;
export default {
data() {
return {
goods: {}
};
},
created() {
this.classMap = ["decrease", "discount", "special", "invoice", "guarantee"];
this.$http.get("/api/goods").then(res => {
console.log(res);
let result = res.data;
if (result.errno == ERR_OK) {
this.goods = result.data;
this.$nextTick(() => { //要在数据请求成功之后再初始化滚动
this._initScroll();
});
}
});
},
methods: {
// 初始化scroll
_initScroll() {
console.log("this.$refs.foodsWrapper--->", this.$refs.foodsWrapper);
console.log("this.$refs.menuWrapper--->", this.$refs.menuWrapper);
this.meunScroll = new BScroll(this.$refs.menuWrapper, {});
this.foodsScroll = new BScroll(this.$refs.foodsWrapper, {});
}
}
};
</script>
<style lang="stylus" scoped>
@import '../../common/stylus/mixin'
@import '../../common/stylus/app'
</style>
二、注意事项
1、要在数据请求回来之后再初始化滚动,因此,我们需要将封装好的滚动方法放到$nextTick中调用
2、要实现滚动的页面或者内容部分中,一个只能存在一个跟标签(不能多个标签并列),例如:
3、当better-scroll不起作用时,先查看是否有下图transition出现,如果没有,则表示没有获取到元素
如果有,则先打印出初始化的结果,查看以下三个字段是否有值,即hasVerticalScroll是否为true,scrollerHeight和wrapperHeight的值是否大于0,当hasVerticalScroll为false,而scrollerHeight和wrapperHeight的值都大于0,这时说明你已经初始化成功了,只是数据不够多,才会出现滑不动的现象(你可以放多点数据上去验证)