记录一下使用vue-better-scroll中遇到的问题
mounted () {
this.scroll = new Bscroll(this.$refs.wrapper, {
mouseWheel: true,
click: true,
tap: true,
disableMouse: false,
disableTouch: false
})
}
在使用vue-better-scroll过程中,一开始我在组件内使用了静态数据渲染列表,但是改成由父组件ajax动态请求数据,再重新传入子组件后,better-scroll无法进行滚动了。
原因:我把better-scroll定义在了组件生命周期mounted中,子组件最开始接收到的父组件数据为空,而此时子组件渲染完成后,better-scroll根据当前的DOM进行渲染,没有数据,wrapper内容不会超出,自然无法滚动。(需要注意的是,ajax数据请求完后,页面是有数据的,即页面看到有数据,better-scroll却无法滚动,因为在数据更新前,better-scroll已经渲染完成了)
解决方法:这是个异步问题,解决方法有很多,如果数据是请求结束后基本不会变动的话,可以把better-scroll的定义放在watch监视器中,但是必须使用vue的$nextTick()
方法,vue的数据变化后,不会立刻将DOM更新,而nextTick方法的作用就是在数据变化后等DOM重新渲染完成后执行。如果数据频繁变动,可以将better-scroll定义在mounted中,然后调用better-scroll的refresh()
方法,重新渲染better-scroll。
// List频繁变动
props: ['List'],
data () {
return {
scroll: null
}
},
mounted () {
this.scroll = new Bscroll(this.$refs.wrapper, {
mouseWheel: true,
click: true,
tap: true,
disableMouse: false,
disableTouch: false
})
},
watch: {
List () {
/*检测到数据变化时,此时如果不使用$nextTick方法,
refresh方法会在DOM更新前直接调用*/
this.$nextTick(() => {
this.scroll.refresh()
})
}
}