javascript / intermediate
Snippet
One-Time Watchers with 'once'
Introduced in Vue 3.4, the 'once' option for watchers ensures the callback only executes the first time the source changes. This is perfect for initialization logic or one-off event reactions that shouldn't persist.
snippet.js
1
2
3
4
5
6
7
8
import { watch, ref } from 'vue';const status = ref('pending');watch(status, (newVal) => {console.log('Status initialized to:', newVal);// Perform setup logic that should only run once}, { once: true });
vue
Breakdown
1
{ once: true }
Tells Vue to automatically stop the watcher after its first successful trigger.