Vue框架中如何每3秒触发一次API请求?
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

