You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue框架中如何每3秒触发一次API请求?

How to Auto-Fetch API Data Every 3 Seconds in Vue

Hey there! I totally get you're just starting out with Vue and want to automatically refresh your page content by calling an API every 3 seconds—let me break this down into simple, actionable steps for you. We'll cover both Vue 3 (the modern Composition API approach) and Vue 2 (Options API) since you might be learning either version.

Core Idea

We'll use JavaScript's setInterval() to schedule repeated API calls, but super important: we need to clean up this timer when the component is destroyed to avoid memory leaks. Also, we'll fetch the data once when the component first loads, so users don't wait 3 seconds for initial content.

For Vue 3 (Composition API with <script setup>)

This is the most common setup for new Vue 3 projects:

<template>
  <div>
    <h2>Latest Data:</h2>
    <p>{{ apiData }}</p>
    <!-- Show loading state if needed -->
    <p v-if="isLoading">Loading...</p>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

// Store API response data
const apiData = ref('');
// Loading state to prevent overlapping requests
const isLoading = ref(false);
// Hold the interval ID so we can clear it later
let intervalId = null;

// Function to fetch data from API
const fetchApiData = async () => {
  isLoading.value = true;
  try {
    const response = await fetch('https://your-api-url-here.com/data');
    const data = await response.json();
    apiData.value = data; // Update your data here
  } catch (error) {
    console.error('Failed to fetch data:', error);
    // Handle error (e.g., show a message to user)
  } finally {
    isLoading.value = false;
  }
};

onMounted(() => {
  // Fetch data immediately when component mounts
  fetchApiData();
  // Set up interval to fetch every 3 seconds (3000 ms)
  intervalId = setInterval(fetchApiData, 3000);
});

onUnmounted(() => {
  // Clear the interval when component is destroyed
  if (intervalId) clearInterval(intervalId);
});
</script>

For Vue 2 (Options API)

If you're working with Vue 2, here's how to implement it:

<template>
  <div>
    <h2>Latest Data:</h2>
    <p>{{ apiData }}</p>
    <p v-if="isLoading">Loading...</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      apiData: '',
      isLoading: false,
      intervalId: null
    };
  },
  methods: {
    async fetchApiData() {
      this.isLoading = true;
      try {
        const response = await fetch('https://your-api-url-here.com/data');
        const data = await response.json();
        this.apiData = data;
      } catch (error) {
        console.error('Failed to fetch data:', error);
      } finally {
        this.isLoading = false;
      }
    }
  },
  mounted() {
    // Initial fetch
    this.fetchApiData();
    // Set up 3-second interval
    this.intervalId = setInterval(this.fetchApiData, 3000);
  },
  beforeDestroy() {
    // Clean up interval to avoid memory leaks
    if (this.intervalId) clearInterval(this.intervalId);
  }
};
</script>

A Pro Tip to Avoid Overlapping Requests

If your API sometimes takes longer than 3 seconds to respond, using setInterval could lead to overlapping requests (multiple calls running at the same time). A safer alternative is to use setTimeout recursively, which waits for the previous request to finish before scheduling the next one:

// Replace the interval setup with this in Vue 3
const scheduleNextFetch = () => {
  setTimeout(async () => {
    await fetchApiData();
    scheduleNextFetch(); // Schedule next call after current one finishes
  }, 3000);
};

onMounted(() => {
  fetchApiData();
  scheduleNextFetch();
});

// Don't forget to store the timeout ID if you need to clear it on unmount!

That's it! Just replace https://your-api-url-here.com/data with your actual API endpoint, and adjust how you handle the response data to fit your page's needs. Let me know if you run into any snags—happy to help further!

内容的提问来源于stack exchange,提问作者WEI A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:02:50