github地址:https://github.com/ustbhuangyi/better-scroll
当 better-scroll 遇见 Vue:https://zhuanlan.zhihu.com/p/27407024
一、安装
npm install better-scroll --save
二、在Vue项目中应用
<template>
<div class="wrapper" ref="wrapper">
<ul class="content">
<li>...</li>
<li>...</li>
...
</ul>
</div>
</template>
<script>
import BScroll from 'better-scroll'
export default {
mounted() {
this.$nextTick(() => {
this.scroll = new Bscroll(this.$refs.wrapper, {})
})
}
}
</script>
三、项目经验
1、scrollToElement 这个方法执行时,会将改元素位置滚动到容器顶部
this.scroll.scrollToElement(element) //element为dom元素
例如:this.scroll.scrollToElement(this.$refs.wrapper)
2、如果 wrapper 中的数据,通过接口请求时,滚动效果不生效
第一种情况:如果数据请求在本组件进行
作者的文章提到,可以将 this.scroll = new Bscroll(this.$refs.wrapper, {}) ,写到接口请求成功并且获取到数据之后。可参考文章开头第2篇文章。
另一种情况:如果是父子组件通信
接口调用是在父组件完成,然后将数据传递给子组件的时候,用第一种方式可能就不太容易。那么可以将 this.scroll 定义在 updated 生命周期函数中。
updated () {
this.scroll = new BScroll(this.$refs.wrapper, {})
},
updated:只有data里的变量改变并且要在页面重新渲染完成之后,才会进updated生命周期,所以可以用这种方式。亲测可行。