SoFunction
Updated on 2025-04-12

Vue implements timed refresh and automatic update (example details)

Timed refresh and automatic update implementation in Vue

In modern web development, timely refreshing pages or timely updating data is a common requirement, especially in scenarios where timely communication with the server or displaying real-time data. Provides simple and effective methods to achieve timing refresh and automatic updates. This article will introduce several common timing refresh methods, applicable scenarios, advantages and disadvantages, and performance considerations.

Refresh page regularly

Timed page refresh is usually suitable for situations where page content needs to be completely reloaded or the entire page status is updated. We can usesetIntervalCall it regularly(), thereby realizing automatic refresh of the page.

Example: Refresh the page every 5 seconds

<template>
  <div>
    <h1>The page will be each 5 Refresh once in seconds</h1>
  </div>
</template>
<script>
export default {
  mounted() {
    // Refresh the page every 5 seconds     = setInterval(() => {
      ();
    }, 5000);
  },
  beforeDestroy() {
    // Clear the timer to avoid the timer still running when the page is destroyed    clearInterval();
  }
}
</script>

explain:

  • setIntervalSet to call every 5 seconds(), refresh the current page.
  • beforeDestroyThe hook is used to clear the timer to prevent the timer from continuing to execute the timing tasks after the component is destroyed and to avoid memory leakage.

Pros and cons

advantage:

  • Suitable for scenarios where the entire page needs to be reloaded, for example: after logging in, the user needs to refresh the page to obtain the latest data, or update a large amount of content in the page.
  • Simple to implement and easy to understand.

shortcoming:

  • Each refresh will reload the entire page, which may result in a poor user experience.
  • Page reloading may result in the loss of other loaded states (such as form data, scrolling positions, etc.).
  • Frequent refreshes may cause unnecessary burdens on the server.

Performance considerations:

  • It is not recommended to refresh the page frequently because each refresh will re-request resources, which increases network bandwidth and server burden.
  • If you only need to update a certain part of the content, you can consider partial updates rather than refreshing the entire page.

Update component data regularly (no page refresh)

If your goal is to update the data of a certain component regularly without refreshing the entire page, you can combine it withsetIntervaland Vue's responsive data mechanism to achieve local refresh. This way, Vue automatically updates the view as the data changes without reloading the page.

Example: Automatically update data every 5 seconds

<template>
  <div>
    <h1>Current time:{{ currentTime }}</h1>
  </div>
</template>
<script>
export default {
  data() {
    return {
      currentTime: new Date().toLocaleTimeString()
    };
  },
  mounted() {
    // Update time every 5 seconds     = setInterval(() => {
       = new Date().toLocaleTimeString();
    }, 5000); // Update every 5 seconds  },
  beforeDestroy() {
    // Clear the timer    clearInterval();
  }
}
</script>

explain:

  • Every 5 seconds,currentTimeThe value of , will be updated to the current time.
  • setIntervalUsed for timed update time.
  • Due to Vue's responsive data mechanism,currentTimeThe view will automatically update when the value of .

Pros and cons

advantage:

  • Only partial content of the component is updated, not the entire page, so the performance is better.
  • The user experience is good, avoiding page flickering or reloading.
  • Flexible and applicable, suitable for obtaining real-time data (such as time, news, stock market, etc.).

shortcoming:

  • The timer needs to be manually cleared when the component is destroyed, otherwise it may cause memory leaks.
  • If the data is updated frequently, the interface may be constantly refreshed and affect the user experience.

Performance considerations:

  • For frequently updated data, the update time interval can be appropriately set to avoid excessively updated and resulting in unnecessary performance losses.
  • Can be used on some non-critical data updatesrequestAnimationFrameto optimize performance, especially in scenarios where smooth transitions are required.

Get data regularly (such as getting data from the API)

In some scenarios, you may need to get data from the server regularly. In this case,setIntervalandaxiosWith the library, you can implement the function of requesting interfaces regularly and updating views.

Example: Get data from the API every 5 seconds

<template>
  <div>
    <h1>API data:{{ data }}</h1>
  </div>
</template>
<script>
import axios from 'axios';
export default {
  data() {
    return {
      data: null
    };
  },
  mounted() {
    // Get data from the API every 5 seconds     = setInterval(() => {
      ('/data')
        .then(response => {
           = ;
        })
        .catch(error => {
          ('Data acquisition failed', error);
        });
    }, 5000); // Request every 5 seconds  },
  beforeDestroy() {
    // Clear the timer    clearInterval();
  }
}
</script>

explain:

  • setIntervalA request is sent to the API every 5 seconds to obtain the latest data.
  • passaxiosGet data and update after successdata
  • beforeDestroyMake sure to clear the timer when the component is destroyed to prevent memory leaks.

Pros and cons

advantage:

  • Get server data in real time and update components, suitable for real-time systems, such as monitoring panels, dynamic content, etc.
  • Using Vue's responsive mechanism, the interface will be automatically updated after updating data.

shortcoming:

  • The timed request API increases the burden on the server, especially when the request interval is short.
  • For users with poor network conditions, frequent requests can lead to delays or failures.

Performance considerations:

  • Adjust the interval of requests appropriately to avoid excessively frequent requests.
  • Unnecessary requests can be reduced through debounce or throttle technology.
  • Consider using cache or lazy loading methods to avoid unnecessary duplicate requests.

usesetTimeoutImplement timing operations (only once)

  • If your requirement is to delay execution of an operation, rather than performing periodically, you can usesetTimeout
  • For example, you can perform an operation after a certain period of time instead of repeating it every once in a while.

Example: Execute the operation after 5 seconds

<template>
  <div>
    <h1>Delay5Perform an operation in seconds</h1>
  </div>
</template>
<script>
export default {
  mounted() {
    setTimeout(() => {
      ('Execute in 5 seconds');
      // Some operations can be performed, such as refreshing data or pages    }, 5000);
  }
}
</script>

explain:

  • usesetTimeoutSet the delay operation and perform an operation after 5 seconds.

Pros and cons

advantage:

  • Suitable for one-time delay operation rather than periodic operation, reducing unnecessary performance consumption.
  • The code is concise and easy to understand.

shortcoming:

  • It can only be used for one-time operations and cannot be repeated.

Performance considerations:

  • usesetTimeoutIt will only be executed once, so there will be no performance overhead for periodic operations.

Summary and optimization suggestions

There are many ways to implement timed refresh or update data in Vue, and the specific choice depends on your needs:

  • If neededRefresh page regularly, can be used(), but be careful that frequent refreshes may affect user experience and server burden.
  • If only requiredUpdate data regularly, using Vue's responsive data andsetIntervalIt is a lightweight option.
  • ifGet server data regularly, can be combinedaxiosandsetIntervalTo implement it, you need to pay attention to the frequency of API requests.
  • forOne-time delay operation, can be usedsetTimeoutto execute.

Performance optimization:

  • Avoid frequent refresh of pages and use local updates instead.
  • useclearIntervalandbeforeDestroyClear the timer to prevent memory leakage.
  • Consider adjusting the request interval and using the caching mechanism in appropriate situations to reduce the request pressure on the server.

The method of choosing timing tasks reasonably according to your needs can help you effectively improve page performance and user experience.

This is the end of this article about the implementation of timed refresh and automatic updates in Vue. For more related content on vue timed refresh and automatic updates, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!