Vue div节点滚动事件-加载更多

使用Vue.directive注册全局指令

Vue.directive('scroll', {})

绑定事件

Vue.directive('scroll', {
  bind: (el, binding, vnode) => {
    
  }
})

对于Vue自定义指令不明白的同学请移步: Vue自定义指令

编写逻辑

Vue.directive('scroll', {
  bind: (el, binding, vnode) => {
    // 距离底部剩余距离开始触发回调
    let distance = 100 // (unit: px)
    // 监听滚动事件
    el.onscroll = (e) => {
        // 获取当前节点可滚动的距离   节点滚动条总高度 - 节点本身高度
       let scrollHeight = e.target.scrollHeight - e.target.offsetHeight
       // 获取节点剩余可滚动的高度   可滚动距离  -  已经滚动的距离
       let residualHeight = scrollHeight - e.target.offsetTop
      //  滚动到指定区域执行回调事件
       if ((typeof binding.value === 'function') && residualHeight < distance) {
        // 执行事件回调函数   如果不明白此处的binding.value的同学请点击上面的链接,自行去官方查看
        binding.value()
      } 
    }
  }
})

阻止回调多次执行

以上代码以及完全实现了加载更多的功能, 但是有个小问题,就是当滚动到 distance 范围之内后就会不断的执行回调, 而有的时候我们只需要执行一次, 其实很简单,请看下面代码, 注意在代码中出行的 eventAction 变量

Vue.directive('scroll', {
  bind: (el, binding, vnode) => {
    // 是否执行回调事件
    let eventAction = true
    // 距离底部剩余距离开始触发回调
    let distance = 100 // (unit: px)
    // 监听滚动事件
    el.onscroll = (e) => {
        // 获取当前节点可滚动的距离   节点滚动条总高度 - 节点本身高度
       let scrollHeight = e.target.scrollHeight - e.target.offsetHeight
       // 获取节点剩余可滚动的高度   可滚动距离  -  已经滚动的距离
       let residualHeight = scrollHeight - e.target.offsetTop
      //  滚动到指定区域执行回调事件
       if ((typeof binding.value === 'function') && residualHeight < distance && eventAction) {
        // 执行事件回调函数   如果不明白此处的binding.value的同学请点击上面的链接,自行去官方查看
        binding.value()
        eventAction = false
      }  else if (residualHeight > distance) {
        eventAction = true
      }
    } 
  }
})

以上代码就可完全正常的工作了, 只需要将其放入Vue脚手架的main.js里面就可以全局使用
使用方法:

<template>
  <div class="result">
    <div class="search" @click="jump({name: 'search', params: {kw: kw}}, false, true)">
      <div class="search-box">
        <div class="input">
          <input type="text" :disabled="true" :value="kw">
        </div>
        <div class="icon font">&#xe61d;</div>
      </div>
    </div>
    <div class="goods" ref="goods" v-scroll="scroll">
      <div
        v-for="(item,idx) in items"
        @click="jump({name: 'product.detail', params: {id: item.id}})"
        :style="{width: itemWidth + 'px', height: (itemWidth + 60) + 'px'}"
        :key="'goods-item-' + idx" class="item">
        <img
          v-lazy="imageUrl + item.thumb"
          :onerror="'this.src=\'' + require('@assets/banner/1.jpg') + '\''"
          :style="{width: itemWidth + 'px', height: itemWidth + 'px'}">
        <div class="item-info">
          <div class="item-title">{{item.title}}</div>
          <div class="price-views">
            <div class="price">¥{{(Number(item.price) / 100).toFixed(2)}}</div>
            <div class="views">
              &nbsp;{{item.views}}<div class="font">&#xe610;</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      imageUrl: this.config('imageUrl'),
      itemWidth: 0,
      items: [],
      page: 1,
      size: 20,
      kw: ''
    }
  },
  methods: {
    scroll () {
      this.getData()
    },
    /**
     * @purpose 获取数据
     */
    getData () {
      this.showLoading()
      this
        .$api
        .goods
        .search(this.kw, this.page, this.size)
        .then(r => {
          if (!(r.list instanceof Array) || r.list.length < 0) {
            return false
          }
          this.items = this.items.concat(r.list)
          this.page++
        })
    }
  },
  mounted () {
    this.itemWidth = (this.$refs.goods.clientWidth - 2) / 2
  },
  created () {
    let kw = this.$route.params.kw
    if (kw) {
      this.kw = kw
      this.getData()
    } else {
      this.toast('缺少搜索关键词!', 2, () => {
        this.jump(-1)
      })
    }
  }
}
</script>
<style scoped lang="sass">
  .result
    width: 100%
    height: 100%
    .search
      width: 100%
      height: 50px
      background-color: #ffffff
      display: flex
      align-items: center
      justify-content: center
      z-index: 100
      .search-box
        width: calc(100% - 20px)
        height: 30px
        display: flex
        align-items: center
        justify-content: center
        background-color: #ebebeb
        border-radius: 20px
        .input
          flex: 1
          height: 100%
          background-color: transparent
          input
            width: calc(100% - 1rem)
            height: 100%
            font-size: 1rem
            background-color: transparent
            margin-left: 1rem
            color: #393a3f
        .icon
          width: 40px
          height: 40px
          font-size: 1rem
          font-weight: bold
          color: #393a3f
          display: flex
          align-items: center
          justify-content: center
          margin-right: .2rem
    .goods
      width: 100%
      height: calc(100% - 51px)
      overflow-x: hidden
      overflow-y: auto
      overflow-scrolling: touch
      .item
        background-color: #ffffff
        margin-bottom: 2px
        float: left
        &:nth-child(2n)
          margin-left: 2px
        .item-info
          width: calc(100% - 10px)
          height: 60px
          padding: 0 5px
          .item-title
            height: 30px
            font-size: .8rem
            line-height: 15px
            overflow: hidden
            text-overflow: ellipsis
            display: -webkit-box
            -webkit-line-clamp: 2
            -webkit-box-orient: vertical
            word-break: break-all
          .price-views
            width: 100%
            height: 30px
            display: flex
            align-items: center
            .price
              flex: 1
              height: 100%
              font-size: .8rem
              color: #ff4700
              display: flex
              align-items: center
            .views
              flex: 1
              height: 100%
              font-size: .6rem
              color: #666666
              display: flex
              align-items: center
              flex-direction: row-reverse
</style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,204评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,091评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,548评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,657评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,689评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,554评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,302评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,216评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,661评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,851评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,977评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,697评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,306评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,898评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,019评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,138评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,927评论 2 355

推荐阅读更多精彩内容