使用vue.js在页面内组件监听scroll事件

思路:scroll在哪儿个组件内,就在获取那个dom元素。网上好多思路是

window.addEventListener("scroll", function(){
        console.log('scrolling');
      });

这是监听不到的!如果你整个网页可以滑动,或许还可以试试!

对于像我这样,只在页面的内的一个div内要监听的。实现代码如下:

第一步:滑动的组件外层的div加 ref="viewBox" 为了通过$refs获取dom元素
<!--设备列表-->
<div class="deviceWrapper" ref="viewBox">
  <mu-refresh-control :refreshing="refreshing" :trigger="trigger" @refresh="refresh"/>
  <div class="demo-grid">
    <!--设备列表 手机一行两列 pad一行4列-->
    <mu-row>
      <mu-col v-for="device in devicesList" width="50" tablet="25" desktop="25">
        <deviceCardView :device-data="device""></devicelightCardView>
      </mu-col>
    </mu-row>
  </div>
  <p class="bottomLine" v-bind:class="{bottomLineVisible:isScroll}">---------------------我是有底线的---------------------</p>
</div>
第二步:
mounted() {
// 通过$refs获取dom元素
  this.box = this.$refs.viewBox
  // 监听这个dom的scroll事件
  this.box.addEventListener('scroll', () => {
    console.log(" scroll " + this.$refs.viewBox.scrollTop)
    //以下是我自己的需求,向下滚动的时候显示“我是有底线的(类似支付宝)”
    this.isScroll=this.$refs.viewBox.scrollTop>0
  }, false)
}
ps:具体怎么做,看需求了。只要能打印出来.scrollTop就行了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章