当前位置:首页 > VUE

vue3中实现接口轮询

2026-01-07 06:30:14VUE

使用 setInterval 实现基础轮询

在 Vue 3 中,可以通过 setInterval 定时调用接口。在组件的 setup 中定义轮询逻辑,注意在组件卸载时清除定时器以避免内存泄漏。

import { onMounted, onUnmounted } from 'vue';
import { fetchData } from './api'; // 替换为实际接口请求方法

export default {
  setup() {
    let pollInterval;

    const pollData = async () => {
      try {
        const response = await fetchData();
        console.log('轮询数据:', response);
      } catch (error) {
        console.error('轮询失败:', error);
      }
    };

    onMounted(() => {
      pollInterval = setInterval(pollData, 5000); // 每5秒轮询一次
    });

    onUnmounted(() => {
      clearInterval(pollInterval);
    });
  }
};

使用 ref 动态控制轮询间隔

通过 ref 动态调整轮询间隔时间,结合 watch 监听间隔变化并重置定时器。

vue3中实现接口轮询

import { ref, watch, onUnmounted } from 'vue';

export default {
  setup() {
    const interval = ref(5000); // 默认5秒
    let timer = null;

    const startPolling = () => {
      timer = setInterval(async () => {
        console.log('执行轮询...');
      }, interval.value);
    };

    watch(interval, (newVal) => {
      clearInterval(timer);
      startPolling();
    });

    onUnmounted(() => clearInterval(timer));

    return { interval };
  }
};

结合 axios 和错误处理

集成 axios 发送请求,增加错误处理和重试机制。通过 retryCount 限制重试次数。

import axios from 'axios';
import { ref, onUnmounted } from 'vue';

export default {
  setup() {
    const data = ref(null);
    const error = ref(null);
    const retryCount = ref(0);
    const maxRetries = 3;
    let pollInterval;

    const fetchData = async () => {
      try {
        const response = await axios.get('https://api.example.com/data');
        data.value = response.data;
        retryCount.value = 0; // 重置重试计数
      } catch (err) {
        error.value = err;
        if (retryCount.value < maxRetries) {
          retryCount.value++;
          setTimeout(fetchData, 2000); // 2秒后重试
        }
      }
    };

    onMounted(() => {
      pollInterval = setInterval(fetchData, 10000); // 每10秒轮询
    });

    onUnmounted(() => clearInterval(pollInterval));

    return { data, error };
  }
};

使用自定义 Hook 封装轮询逻辑

将轮询逻辑抽象为可复用的自定义 Hook,提升代码复用性。

vue3中实现接口轮询

// usePolling.js
import { ref, onUnmounted } from 'vue';

export function usePolling(fetchFn, interval = 5000) {
  const data = ref(null);
  const error = ref(null);
  let pollTimer;

  const startPolling = () => {
    const execute = async () => {
      try {
        data.value = await fetchFn();
        error.value = null;
      } catch (err) {
        error.value = err;
      }
    };
    execute(); // 立即执行一次
    pollTimer = setInterval(execute, interval);
  };

  const stopPolling = () => {
    clearInterval(pollTimer);
  };

  onUnmounted(stopPolling);

  return { data, error, startPolling, stopPolling };
}

在组件中使用自定义 Hook:

import { usePolling } from './usePolling';
import { fetchUser } from './api';

export default {
  setup() {
    const { data, error } = usePolling(fetchUser, 3000);
    return { data, error };
  }
};

轮询条件控制

通过条件判断决定是否继续轮询,例如根据接口返回的特定字段终止轮询。

const shouldContinue = ref(true);

const checkStatus = async () => {
  const res = await fetchStatus();
  if (res.status === 'completed') {
    shouldContinue.value = false;
    clearInterval(pollInterval);
  }
};

const pollInterval = setInterval(() => {
  if (shouldContinue.value) checkStatus();
}, 2000);

标签: 接口
分享给朋友:

相关文章

vue实现接口

vue实现接口

在 Vue 中实现接口请求 Vue 本身不直接提供 HTTP 请求功能,通常需要借助第三方库如 axios 或 fetch 来实现接口请求。以下是几种常见方法: 使用 axios 发送请求 安装 a…

vue调用后台接口实现

vue调用后台接口实现

Vue 调用后台接口的实现方法 在 Vue 中调用后台接口通常涉及以下几个关键步骤: 安装必要的依赖 确保项目中安装了 axios 或 fetch 等 HTTP 请求库。通过以下命令安装 axios…

java如何写接口

java如何写接口

定义接口 在Java中,使用interface关键字定义接口。接口可以包含抽象方法、默认方法、静态方法和常量(隐式为public static final)。 public interface…

php实现支付宝接口

php实现支付宝接口

支付宝接口集成方法 在PHP中实现支付宝接口需要完成以下几个关键步骤。支付宝官方提供了多种接口类型,如即时到账、手机网站支付、APP支付等,以下以即时到账接口为例说明。 准备工作 注册支付宝企业账…

vue实现接口测试

vue实现接口测试

Vue 实现接口测试的方法 在 Vue 项目中实现接口测试,可以通过多种方式完成。以下是几种常见的方法: 使用 Axios 进行接口测试 Axios 是 Vue 中常用的 HTTP 客户端库,…

vue实现登录调用接口

vue实现登录调用接口

Vue 登录接口调用实现 安装 axios 在项目中安装 axios 用于发送 HTTP 请求: npm install axios 创建 API 服务文件 在 src 目录下创建 api/auth…