Vue Tip: Using Once Watchers
In Vue.js, a watcher's callback function executes every time the watched source changes. However, there might be scenarios where you only want the callback to trigger once on the initial change. This is where the once: true option comes in handy.
How to Use Once Watchers
By default, Vue watchers are designed to listen to changes continuously. To alter this behavior so that the callback is triggered only once, you can simply add the once: true option when defining your watcher.
Example:
<script setup lang="ts">
watch(
source,
(newValue, oldValue) => {
// when the source changes, triggers only once
},
{ once: true }
)
</script>
In this example, the watcher on the source will trigger the callback when the source changes, but only once. Subsequent changes to source will not trigger the callback.
Benefits of Using Once Watchers
Performance Optimization: Reduces the number of times the callback is executed, which can be particularly useful in performance-sensitive applications.
Simpler Logic: Avoids the need for additional logic to ensure a callback only runs once.
Use the once: true option to streamline your Vue watchers and improve the efficiency of your reactive code.
Top comments (0)