当前位置:首页 > VUE

vue 实现下拉刷新

2026-02-22 09:59:29VUE

vue 实现下拉刷新的方法

使用第三方库(如vant)

安装vant库的PullRefresh组件,快速实现下拉刷新功能。

vue 实现下拉刷新

npm install vant

在组件中引入并使用:

<template>
  <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <!-- 列表内容 -->
  </van-pull-refresh>
</template>

<script>
import { PullRefresh } from 'vant';
export default {
  components: {
    [PullRefresh.name]: PullRefresh
  },
  data() {
    return {
      isLoading: false
    };
  },
  methods: {
    onRefresh() {
      setTimeout(() => {
        // 刷新数据逻辑
        this.isLoading = false;
      }, 1000);
    }
  }
};
</script>

原生实现方案

通过监听touch事件实现自定义下拉刷新。

<template>
  <div class="refresh-container" 
       @touchstart="touchStart" 
       @touchmove="touchMove" 
       @touchend="touchEnd">
    <div class="refresh-control" :style="{ transform: `translateY(${distance}px)` }">
      <!-- 下拉提示内容 -->
    </div>
    <!-- 列表内容 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      startY: 0,
      distance: 0,
      isLoading: false
    };
  },
  methods: {
    touchStart(e) {
      this.startY = e.touches[0].pageY;
    },
    touchMove(e) {
      const currentY = e.touches[0].pageY;
      if (currentY - this.startY > 0 && window.scrollY <= 0) {
        this.distance = currentY - this.startY;
      }
    },
    touchEnd() {
      if (this.distance > 50) {
        this.isLoading = true;
        this.onRefresh();
      }
      this.distance = 0;
    },
    onRefresh() {
      // 数据刷新逻辑
      setTimeout(() => {
        this.isLoading = false;
      }, 1000);
    }
  }
};
</script>

<style>
.refresh-container {
  position: relative;
  overflow: hidden;
}
.refresh-control {
  position: absolute;
  width: 100%;
  text-align: center;
  transition: transform 0.3s;
}
</style>

注意事项

  • 移动端需要添加viewport meta标签确保触摸事件正常触发
  • 下拉距离阈值建议设置为50-80px
  • 刷新完成后需要重置状态和动画
  • 列表内容需要确保有足够高度才能触发下拉

两种方案各有优势,第三方库实现更快捷,原生方案可控性更强。根据项目需求选择合适方案。

vue 实现下拉刷新

标签: vue
分享给朋友:

相关文章

vue伪函数实现

vue伪函数实现

Vue 伪函数实现方法 伪函数(Mock Function)在 Vue 中常用于测试或模拟某些逻辑,以下是几种常见的实现方式: 使用 Jest 的 jest.fn() 在单元测试中,可以通过 Jes…

vue实现文字播放栏

vue实现文字播放栏

Vue 实现文字播放栏(跑马灯效果) 方法一:使用 CSS 动画 + Vue 数据绑定 通过 CSS 的 @keyframes 实现动画效果,结合 Vue 的动态数据绑定控制内容。 <t…

vue实现一个标签选择

vue实现一个标签选择

Vue 标签选择组件实现 基础实现 使用 Vue 的 v-for 和 v-model 指令可以快速实现标签选择功能: <template> <div class="tag-se…

vue实现高亮

vue实现高亮

Vue 实现文本高亮的方法 在 Vue 中实现文本高亮可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-html 指令 通过 v-html 指令可以动态插入 HTML 内容,将需要高…

vue实现节流

vue实现节流

vue实现节流的方法 在Vue中实现节流(throttle)功能,通常用于限制高频事件的触发频率,例如滚动、输入或按钮点击。以下是几种常见的实现方式: 使用Lodash的throttle函数 安装L…

vue 全景实现

vue 全景实现

Vue 全景实现方案 在Vue中实现全景效果,通常需要结合WebGL或第三方库来处理3D场景渲染。以下是几种常见方法: 使用Three.js库 Three.js是一个强大的WebGL库,适合创建…