当前位置:首页 > VUE

vue3中实现接口轮询

2026-03-27 06:13:15VUE

vue3 中实现接口轮询的方法

使用 setInterval 实现基础轮询

在 Vue3 的 setup 中通过 setInterval 定时调用接口:

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

const data = ref(null)
let pollInterval = null

const fetchData = async () => {
  try {
    const response = await axios.get('/api/data')
    data.value = response.data
  } catch (error) {
    console.error('轮询请求失败:', error)
  }
}

onMounted(() => {
  pollInterval = setInterval(fetchData, 5000) // 每5秒请求一次
})

onUnmounted(() => {
  clearInterval(pollInterval) // 组件卸载时清除定时器
})

使用 setTimeout 实现可调节间隔的轮询

更灵活的递归调用方式,可根据响应结果动态调整间隔:

const pollWithTimeout = async (interval = 5000) => {
  await fetchData()
  setTimeout(() => pollWithTimeout(interval), interval)
}

onMounted(() => {
  pollWithTimeout()
})

带错误处理的增强版轮询

增加错误重试机制和最大重试次数限制:

const MAX_RETRIES = 3
let retryCount = 0

const fetchDataWithRetry = async () => {
  try {
    const response = await axios.get('/api/data')
    data.value = response.data
    retryCount = 0 // 成功时重置重试计数
  } catch (error) {
    if (retryCount < MAX_RETRIES) {
      retryCount++
      console.log(`第 ${retryCount} 次重试...`)
    } else {
      console.error('达到最大重试次数')
      clearInterval(pollInterval)
    }
  }
}

使用 Web Worker 实现后台轮询

避免主线程阻塞的解决方案:

// worker.js
self.onmessage = function(e) {
  setInterval(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(data => self.postMessage(data))
  }, e.data.interval)
}

// 组件中
const worker = new Worker('./worker.js')
worker.onmessage = (e) => {
  data.value = e.data
}
onUnmounted(() => worker.terminate())

基于 Composition API 的复用方案

封装成可复用的 composable 函数:

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

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

  const start = () => {
    const execute = async () => {
      data.value = await fetchFn()
      timer = setTimeout(execute, interval)
    }
    execute()
  }

  const stop = () => {
    clearTimeout(timer)
  }

  onUnmounted(stop)

  return { data, start, stop }
}

// 组件中使用
import { usePolling } from './usePolling'

const { data } = usePolling(async () => {
  const res = await axios.get('/api/data')
  return res.data
}, 3000)

智能轮询策略(根据网络状态调整)

通过 navigator.onLine 检测网络状态优化轮询:

vue3中实现接口轮询

const adaptivePolling = () => {
  if (!navigator.onLine) {
    console.log('网络离线,暂停轮询')
    return
  }

  fetchData()
  const delay = data.value?.priority ? 2000 : 5000
  setTimeout(adaptivePolling, delay)
}

每种方法适用于不同场景,基础项目可使用简单 setInterval 方案,复杂应用建议采用 composable 封装或 Web Worker 方案。注意组件卸载时务必清除定时器,避免内存泄漏。

标签: 接口
分享给朋友:

相关文章

php实现支付宝接口

php实现支付宝接口

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

react如何在model层写函数调接口

react如何在model层写函数调接口

React 中 Model 层函数调用接口的实现 在 React 应用中,Model 层通常负责数据管理和接口调用。可以通过以下方式组织代码: 创建独立的 API 服务模块 将接口调用封装在单独的…

php接口怎么实现

php接口怎么实现

PHP 接口实现方法 在 PHP 中,接口(Interface)用于定义一组方法的规范,而不包含具体实现。接口通过 interface 关键字定义,类通过 implements 关键字实现接口。 定…

php实现支付接口

php实现支付接口

PHP 支付接口实现方法 支付接口的整合通常需要与第三方支付平台(如支付宝、微信支付、PayPal等)对接。以下是实现支付接口的常见方法。 选择支付平台 根据业务需求选择合适的支付平台,国内常见的有…

php接口实现

php接口实现

PHP接口实现方法 定义接口 使用interface关键字定义接口,接口中只能包含抽象方法和常量。接口方法必须是公开的,且不包含具体实现。 interface LoggerInterface {…

java如何写一个接口

java如何写一个接口

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