内容区滚动组件封装

温馨提示:让iscroll内容滚动,首先iscroll容器的高度,必须小于内容区的高度
没设置内容区的高度就滚动不了了
容器的高等于可视区的高度,可视区就人所看得到的屏幕大小

安装

yarn add iscroll

配置

  • 滚动组件封装
// src/components/ScrollView
<div id="wrapper" ref="wrapper">
  <!-- 插槽 -->
  <slot></slot>
</div>

#wrapper{
  width: 100%;
  height: 100%;
}
  • 初始化
// src/components/ScrollView
  mounted () {
    this.iscroll = new IScroll(this.$refs.wrapper, {
      mouseWheel: true, // 禁用鼠标滚轮
      scrollbars: false, // 禁用滚轮条
      probeType: 3,
      // 解决拖拽卡顿问题
      scrollX: false,
      scrollY: true,
      disablePointer: true,
      disableTouch: false,
      disableMouse: true
    })
    // 1.创建一个观察者对象
    /*
    MutationObserver构造函数只要监听到了指定内容发生了变化, 就会执行传入的回调函数
    mutationList: 发生变化的数组
    observer: 观察者对象
    * */
    let observer = new MutationObserver((mutationList, observer) => {
      // console.log(mutationList)
      // console.log(this.iscroll.maxScrollY)
      this.iscroll.refresh()
      // console.log(this.iscroll.maxScrollY)
    })
    // 2.告诉观察者对象我们需要观察什么内容
    let config = {
      childList: true, // 观察目标子节点的变化,添加或者删除
      subtree: true, // 默认为 false,设置为 true 可以观察后代节点
      attributeFilter: ['height', 'offsetHeight'] // 观察特定属性
    }
    // 3.告诉观察者对象, 我们需要观察谁, 需要观察什么内容
    /*
    第一个参数: 告诉观察者对象我们需要观察谁
    第二个参数: 告诉观察者对象我们需要观察什么内容
    * */
    observer.observe(this.$refs.wrapper, config)
  },
  methods: {
    // 提供一个监听滚动距离的方法给外界使用
    scrolling (fn) {
      this.iscroll.on('scroll', function () {
        fn(this.y)
      })
    },
    refresh () {
      setTimeout(() => {
        this.iscroll.refresh()
      }, 100)
    },
    scrollTo (x, y, time) {
      this.iscroll.scrollTo(x, y, time)
    }
  }
}

组件中使用

// src/app
<div id='app'>
    <ScrollView>
        <div>这里就是写内容部分啦!</div>
    </ScrollView>
</div>

样式的设置

html,
body {
    width: 100%;
    height: 100%;
    overflow: hidden;
    // 解决IScroll拖拽卡顿问题
    touch-action: none;
}

/* 可视区 */
#app{
  position: fixed;
  top: 184px;
  left: 0;
  right: 0;
  bottom: 0;
}
posted @ 2022-08-28 22:08  天使阿丽塔  阅读(30)  评论(0编辑  收藏  举报