1 导入iscroll
npm i iscroll
在需要用的地方导入iscroll
- 这里将scroll抽离成组件 要用到的地方就导入
- 新建一个scrollView组件
<template>
<div id="wrapper" ref="wrapper">
<slot></slot>
</div>
</template>
<script>
import IScroll from 'iscroll/build/iscroll-probe'
export default {
mounted () {
this.iscroll = new IScroll('#wrapper', {
mouseWheel: true,
scrollbars: true
})
setTimeout(() => {
console.log(this.iscroll.maxScrollY)
this.iscroll.refresh()
console.log(this.iscroll.maxScrollY)
}, 5000)
}
}
</script>
<style lang="scss" scoped>
#wrapper {
width: 100%;
height: 100%;
}
</style>
3 在用到的地方导入这个组件
<scroll-view>
<div>
// 需要滚动的组件
<a/>
<b/>
</div>
</scroll-view>
4 在base.scss配置
html, body{
width: 100%;
height: 100%;
overflow: hidden;
touch-action: none;
}
5 此时页面可以滚动但是 还是会有点卡顿 所以在iscrollView的mouted钩子函数中添加一段代码
this.iscroll = new IScroll('#wrapper', {
mouseWheel: true,
scrollbars: true,
scrollX: false,
scrollY: true,
disablePointer: true,
disableTouch: false,
disableMouse: true
})
6 这里使用MutationObser构造函数来监听dom的变化 不使用定时器
- MutationObser( mutationList,observe) 接收两个参数
- mutationList: 发生变化的数组
- observe: 观察者对象
- observe 观察者接收两个参数
- 第一个参数:告诉观察者需要监听谁
- 第二个参数:告诉观察者监听什么内容
6.1 MutatioObser特点
- 它等待所有脚本任务完成后,才会运行,即采用异步方式
- 它把DOM变动记录封装成一个数组进行处理,而不是一条条地个别处理DOM变动。
- 它即可以观察发生在DOM节点的所有变动,也可以观察某一类变动
const observe = new MutationObser((mutationList,observe)=>{
this.iscroll.refresh()
})
const config = {
childList: true,
subtree: true,
attributeFilter: ['height', 'offsetHeight']
}
observ.observe(this.$refs.wrapper,config)
<template>
<div id="wrapper" ref="wrapper">
<slot></slot>
</div>
</template>
<script>
import IScroll from 'iscroll/build/iscroll-probe'
export default {
name: 'scrollView',
mounted () {
this.iscroll = new IScroll(this.$refs.wrapper, {
mouseWheel: true,
scrollbars: true,
scrollX: false,
scrollY: true,
disablePointer: true,
disableTouch: false,
disableMouse: true
})
const observe = new MutationObserver(() => {
this.iscroll.refresh()
})
const config = {
childList: true,
subtree: true,
attributeFilter: ['height', 'offsetHeight']
}
observe.observe(this.$refs.wrapper, config)
}
}
</script>
<style lang="scss" scoped>
#wrapper {
width: 100%;
height: 100%;
}
</style>