VueJS定时GET请求重复数据问题:如何避免重复与卡顿?
Solution to Prevent Duplicate Data & Fix Update Errors
Key Issues in Your Code
- Duplicate Entries: You’re appending new data to existing
symbols/pricearrays instead of replacing them, leading to repeated symbols and "Duplicate keys" errors. - Useless
awaitonforEach:forEachdoesn’t return a promise, so addingawaithere has no effect. - Overly Frequent Requests: 500ms intervals trigger excessive API calls, causing performance lag and potential rate limiting.
Step-by-Step Fixes
Replace Data Entirely Instead of Appending
Generate fresh arrays from each API response and overwrite the old data to eliminate duplicates:methods: { async fetchApi() { try { const response = await fetch('https://api2.binance.com/api/v3/ticker/24hr'); if (!response.ok) throw new Error(`HTTP status: ${response.status}`); const data = await response.json(); // Create new arrays with the latest ticker data const newSymbols = data.map(item => item.symbol); const newPrices = data.map(item => +item.lastPrice); // Replace existing data to avoid duplicates this.chartData.symbols = newSymbols; this.chartData.price = newPrices; } catch (error) { console.error('Failed to fetch data:', error); } } }Adjust Interval Timing
- For testing: Use a longer interval (e.g., 10 seconds =
10000ms) to avoid overwhelming your app and the API. - For production: Set to 20 minutes (
20 * 60 * 1000 = 1200000ms):
async created() { this.loaded = false; // Test interval: 10s, production: 1200000ms this.timer = setInterval(this.fetchApi, 10000); this.loaded = true; }- For testing: Use a longer interval (e.g., 10 seconds =
Clean Up Interval to Avoid Memory Leaks
Clear the interval when the component is unmounted to prevent unnecessary background requests:beforeUnmount() { clearInterval(this.timer); }
Additional Notes
- Ensure your template uses unique keys (e.g.,
:key="symbol"inv-for)—this error will disappear now thatsymbolscontains no duplicates. - The Binance API returns the full list of tickers on each request, so replacing the entire array is the most efficient way to keep data up-to-date.
内容的提问来源于stack exchange,提问作者theplaceofburak
相关产品推荐
相关产品推荐

