Vue实现下拉刷新组件(简单明了)

笔者在写这篇文章时,刚刚完成了下拉组件的封装,还热乎着。迫不及待的想分享给大家。在这之前,如果你跟我一样带着些迷惑和好奇,想要自己动手完成一些框架中的组件并了解其原理。希望这篇文章可以帮到你。

一、首先分析一下,他的核心是什么,你或许应该想到了,那就是下拉到一定位置后,手指离开屏幕就触发一个函数,听起来不难,但过程中我还是遇到了一些逻辑的问题,逻辑搞懂了,so easy,我就直接上代码了

<template>
  <div
    class="weui-pull-refresh"
    ref="scrollBox"
    :style="style"
    @touchstart="touchStart"
    @touchmove="touchMove"
    @touchend="touchEnd">
    <div class="weui-pull-refreshing-box">
      <div v-if="moveState < 2">{{ moveState === 0 ? '下拉即可刷新...' : '释放即可刷新...' }}</div>
      <div v-else><i class="weui-loading"/> 加载中...</div>
    </div>
    <div class="weui-pull-present-box">
      <slot/>
    </div>
  </div>
</template>

<script>
//如果你想直接拿来用,把create干掉
import { create } from '../../utils'
//create()干掉
export default create({
  name: 'pull-refresh',
  data () {
    return {
      startY: '',    //保存touch时的Y坐标
      moveDistance: 0,    //保存向下滑动的距离
      moveState: 0,        //开始滑动到结束后状态的变化 0:下拉即可刷新 1:释放即可刷新 2:加载中
      duration: 0        //动画持续时间,0就是没有动画
    }
  },
  computed: {
    style () {
      return {
        transition: `${this.duration}ms`,
        transform: `translate3d(0,${this.moveDistance}px, 0)`
      }
    }
  },
  methods: {
    touchStart (e) {
      this.duration = 0 // 关闭动画
      this.moveDistance = 0 // 滑动距离归0
      this.startY = e.targetTouches[0].clientY  // 获得开始Y坐标
    },
    touchMove (e) {    //这里是整个下拉刷新的核心
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        //首先判断我们有没有滚动条,如果有,我们下拉刷新就不能启用。
      if (scrollTop > 0) return

      let move = e.targetTouches[0].clientY - this.startY
        //判断手指滑动的距离,只有为正数才代表用户下拉了。
      if (move > 0) {
        //阻止默认事件,在微信浏览器中尤为有用,至于为什么,你去试就知道了。
        e.preventDefault()
        //增加滑动阻力的感觉
        this.moveDistance = Math.pow(move, 0.8)
        if (this.moveDistance > 50) {
        //如果滑动距离大于50 那我就告诉你,释放即可刷新
          if (this.moveState === 1) return
          this.moveState = 1
        } else {
        //否则 恢复原样
          if (this.moveState === 0) return
          this.moveState = 0
        }
      }
    },
    touchEnd (e) {
      // 只要手指拿开,我都需要加上结束时的动画,这里为300ms
      this.duration = 300
      if (this.moveDistance > 50) {
        //这里逻辑跟touchMove一样,但是需要真的加载数据了,那moveState变为2 所以加载动画在这出现
        this.moveState = 2
        //因为还没加载完,我得让加载动画显示着,所以这里移动距离为50
        this.moveDistance = 50
        this.$emit('refresh', () => {
            //这里就是成功后的回调了,如果该函数被调用,那就以为着加载数据完成,所以状态要回到0,当然需要在父组件调用。
          this.moveState = 0
        })
      } else {
        //否则 给我老老实实恢复原样
        this.moveDistance = 0
      }
    }
  },
  watch: {
    //这里是给用户操作返回的核心
    moveState (state) {
      //我们监听moveState的状态,
      //0意味着开始也意味着结束,这里是结束,并且只有动画生效我们才能 moveDistance 设为0,
      //为什么动画生效才行,因为动画生效意味着手指离开了屏幕,如果不懂去看touchEnd方法,这时
      //我们让距离变为0才会有动画效果。
      if (state === 0 && this.duration === 300) {
        this.moveDistance = 0
      }
    }
  }
})
</script>
<!-- css我就不讲了,你肯定比我厉害 -->
<style scoped lang="scss">
  .weui-pull-refresh {
      display: flex;
      height: calc(100vh - 50px);
      flex-direction: column;
      margin-top: -50px;
      .weui-pull-refreshing-box {
          line-height: 50px;
          height: 50px;
          font-size: 14px;
          color: rgba(69,90,100,.6);
          text-align: center;
          margin-bottom:20px;
      }
      .weui-pull-present-box {
          background-color: lighten(#fff, 10%);
      }
  }
</style>

二、调用:

<template>
  <wv-pull-refresh @refresh="refresh">
    <div class="content">
      <p class="text">基础用法</p>
      刷新次数:{{ num }}
    </div>
  </wv-pull-refresh>
</template>

<script>
export default {
  data () {
    return {
      num: 0
    }
  },
  methods: {
    refresh (done) {
      setTimeout(() => {
        this.num++
        done()    //我就想说这里,把状态归0
      }, 500)
    }
  }
}
</script>

<style scoped lang="scss">
.content{
  padding:0 15px;
  .text{
    font-size: 14px;
    color: rgba(69,90,100,.6);
  }
}
</style>

这就完成了,如果你用的过程中出现BUG,欢迎留言。若有好的建议,欢迎来探讨。

  • 22
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 27
    评论
下拉刷新是移动端 APP 中常见的交互方式,可以提高用户体验,因此我们可以将其封装成一个组件,方便在多个页面中复用。下面是一个简单的 Vue 下拉刷新组件实现: ```html <template> <div class="pull-refresh-wrapper"> <div class="pull-refresh-status" :class="{'loading': isLoading}"> <div class="pull-refresh-icon"></div> <div class="pull-refresh-text">{{ text }}</div> </div> <div class="pull-refresh-content" ref="content"> <slot></slot> </div> </div> </template> <script> export default { props: { threshold: { type: Number, default: 80 }, text: { type: String, default: '下拉刷新' } }, data() { return { startY: 0, isLoading: false, isDragging: false }; }, mounted() { this.$refs.content.addEventListener('touchstart', this.handleTouchStart); this.$refs.content.addEventListener('touchmove', this.handleTouchMove); this.$refs.content.addEventListener('touchend', this.handleTouchEnd); }, beforeDestroy() { this.$refs.content.removeEventListener('touchstart', this.handleTouchStart); this.$refs.content.removeEventListener('touchmove', this.handleTouchMove); this.$refs.content.removeEventListener('touchend', this.handleTouchEnd); }, methods: { handleTouchStart(e) { this.startY = e.touches[0].clientY; }, handleTouchMove(e) { if (this.isLoading) { return; } const currentY = e.touches[0].clientY; const distance = currentY - this.startY; if (distance > 0 && this.$refs.content.scrollTop === 0) { this.isDragging = true; e.preventDefault(); if (distance >= this.threshold) { this.text = '松开刷新'; } else { this.text = '下拉刷新'; } } else { this.isDragging = false; } }, handleTouchEnd() { if (this.isLoading || !this.isDragging) { return; } if (this.text === '松开刷新') { this.isLoading = true; this.text = '正在刷新'; this.$emit('refresh', () => { this.isLoading = false; this.text = '下拉刷新'; }); } else { this.text = '下拉刷新'; } this.isDragging = false; } } }; </script> <style> .pull-refresh-wrapper { height: 100%; overflow: hidden; } .pull-refresh-status { height: 80px; display: flex; align-items: center; justify-content: center; font-size: 14px; color: #666; } .pull-refresh-icon { width: 16px; height: 16px; margin-right: 8px; border-radius: 50%; border: 2px solid #666; border-top-color: transparent; animation: spin 0.6s linear infinite; } .pull-refresh-text { white-space: nowrap; } .pull-refresh-content { height: calc(100% - 80px); overflow-y: auto; } .loading .pull-refresh-icon { border-color: #42b983; border-top-color: transparent; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style> ``` 在上面的代码中,我们使用了 touch 事件来实现下拉刷新。当用户下拉到一定程度时,组件会触发 refresh 事件,我们可以在该事件中进行数据的异步请求。在请求完成后,将 isLoading 设为 false 即可停止 loading 状态。 另外,我们使用了 slot 来插入需要刷新的内容,并监听了 touchstart、touchmove 和 touchend 事件来处理下拉刷新的逻辑。其中,handleTouchMove 方法用于判断下拉距离是否达到阈值,并改变刷新文本的内容;handleTouchEnd 方法用于处理下拉刷新的触发事件,如果下拉距离达到阈值,则触发 refresh 事件,并将 isLoading 设为 true,同时改变刷新文本的内容为“正在刷新”。在事件处理函数中,我们使用了箭头函数来确保 this 指向正确。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值