当前位置:首页 > 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 中实现接口分页通常需要结合后端 API 和前端分页组件。以下是常见的实现方式: 使用 Element UI 的分页组件 安装 Element UI 后,可以使…

vue实现登录调用接口

vue实现登录调用接口

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

如何实现vue数据接口

如何实现vue数据接口

实现Vue数据接口的方法 在Vue中实现数据接口通常涉及与后端API的交互,可以通过多种方式完成。以下是几种常见的方法: 使用axios发送HTTP请求 axios是一个流行的HTTP客户端,适用…

Vue调接口怎么实现

Vue调接口怎么实现

Vue调用接口的实现方法 在Vue中调用接口通常使用axios或fetch等HTTP客户端库,以下是具体实现方式: 安装axios 通过npm或yarn安装axios依赖: npm install…

php实现接口轮询

php实现接口轮询

PHP实现接口轮询的方法 轮询是一种客户端定期向服务器发送请求以获取最新数据的技术。以下是几种常见的PHP实现方式: 基础HTTP轮询实现 使用简单的循环和sleep函数实现基本轮询: $url…

java如何写一个接口

java如何写一个接口

在Java中编写接口的基本语法 接口使用interface关键字定义,可以包含抽象方法、默认方法、静态方法和常量。以下是基础语法示例: public interface MyInterface {…