Basic examples
Computational properties allow us to declaratively calculate derivative values. However, in some cases, we need to perform some "side effects" when the state changes: such as changing the DOM, or modifying the state in another place based on the results of an asynchronous operation.
In the combined API, we can usewatch functionTrigger the callback function every time the responsive state changes:
<script setup> import { ref, watch } from 'vue' const question = ref('') const answer = ref('Questions usually contain a question mark. ;-)') const loading = ref(false) // You can listen to a ref directlywatch(question, async (newQuestion, oldQuestion) => { if (('?')) { = true = 'Thinking...' try { const res = await fetch('/api') = (await ()).answer } catch (error) { = 'Error! Could not reach the API. ' + error } finally { = false } } }) </script> <template> <p> Ask a yes/no question: <input v-model="question" :disabled="loading" /> </p> <p>{{ answer }}</p> </template>
Listen to data source type
The first parameter of the watch can be a different form of "data source": it can be a ref (including computed properties), a responsive object, a getter function, or an array of multiple data sources:
const x = ref(0) const y = ref(0) // Single refwatch(x, (newX) => { (`x is ${newX}`) }) // getter functionwatch( () => + , (sum) => { (`sum of x + y is: ${sum}`) } ) // Array of multiple sourceswatch([x, () => ], ([newX, newY]) => { (`x is ${newX} and y is ${newY}`) })
Note that you cannot directly listen for property values of responsive objects, for example:
const obj = reactive({ count: 0 }) // Error, because the parameter obtained by watch() is a numberwatch(, (count) => { (`count is: ${count}`) })
Here you need to use a getter function that returns this property:
// Provide a getter functionwatch( () => , (count) => { (`count is: ${count}`) } )
Deep Listener
Passing a responsive object directly to watch() will implicitly create a deep listener - the callback function will be triggered during all nested changes:
const obj = reactive({ count: 0 }) watch(obj, (newValue, oldValue) => { // Triggered when nested property changes // Note: `newValue` is equal here and `oldValue` // Because they are the same object!}) ++
In contrast, a getter function that returns a responsive object will trigger a callback only when a different object is returned:
js
watch( () => , () => { // Triggered only if replaced } )
You can also explicitly add the deep option to the example above and force it to a deep listener:
watch( () => , (newValue, oldValue) => { // Note: `newValue` is equal here and `oldValue` // *Unless * is replaced by the entire }, { deep: true } )]
This is the end of this article about the detailed explanation of the use of listeners in vue. For more related vue listeners, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!