- 环境准备
安装better-scroll
npm install --save better-scroll
- 引入better-scroll
import BScroll from "better-scroll"
实现左右滚动
使用BScroll实例化之前必需要等待DOM渲染完成。
产生左右滚动的条件是子盒子内的宽度必须要大于父盒子的宽度,所以我们在用better-scroll时,必须要先得到滚动区域的尺寸和父盒子的尺寸,来计算出是否能滚动。
- 下面是一个小demo
<template>
<div ref="content" class="content"> // 父盒子--滚动区域
<ul ref="child" class="child"> // 子盒子-内容区域
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>
</template>
(1)class为content的div的父盒子,在此区域内滚动,需要通过ref拿到DOM。
(2)ul元素是子盒子,包含若干个li元素,可以通过li元素的宽度动态进行计算,也可以通过ref获取dom
<style lang="stylus" scoped>
.content{
touch-action: none
padding 15px
ul{
li{
width 90px
height 90px
display inline-block
background #eee
line-height 90px
text-align center
}
}
}
</style>
给li标签90px的宽度,确保子盒的宽度大于父盒子的宽度
- 使用better-scroll
import BScroll from 'better-scroll'
export default {
mounted () {
this.$nextTick(() => {
this.leftToRightScroll()
})
},
methods: {
leftToRightScroll () {
let liList = document.querySelectorAll('li')
let width = liList.length * liList[0].offsetWidth // 动态计算出内容区域的大小
this.$refs.child.style.width = width + 'px' // 修改子盒子区域的宽度
this.$nextTick(() => {
// 确保DOM已渲染
if (!this.scroll) {
this.scroll = new BScroll(this.$refs.content, {
startX: 0,
click: true,
scrollX: true,
scrollY: false,
eventPassthrough: 'vertical',
})
} else {
this.scroll.refresh() // dom发生改变会刷新
}
})
},
},
}
(1) 首先拿到所有的li元素的宽度,赋值给ul元素
(2) 生成BScroll实例,其中this.$refs.content就是父盒子的DOM,在此区域内滚动。
实现上下滚动
<template>
<div ref="content" class="content"> // 父盒子--滚动区域
<ul ref="child" class="child"> // 子盒子-内容区域
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>
</template>
<style lang="stylus" scoped>
.content{
margin-top 200px
height 200px
overflow hidden
touch-action: none
padding 15px
ul{
li{
width 90px
height 50px
background #eee
line-height 90px
text-align center
}
}
}
</style>
需要给父元素一个固定的高度,并且overflow属性为hidden
- 使用better-scroll
mounted () {
this.$nextTick(() => {
let contentDom = this.$refs.content
this.scroll = new BScroll(contentDom, {})
})
}
解决better-scroll点击事件失效
只需要在配置参数
this.scroll = new BScroll(this.$refs.content, {
click: true
})
click为true即可。