Watch introduction
Watch in vue is used to monitor the responsive changes of data. Get the values before and after the data changes
Complete entry of watch
watch(Listening data,Side Effects Function,Configuration Objects) watch(data, (newData, oldData) => {}, {immediate: true, deep: true})
Different situations of watch monitoring
Create responsive data
import { ref, watch, reactive } from "vue"; let name = ref("moxun"); let age = ref(18); let person = reactive({ Hobby: "photo", city: { jiangsu: { nanjing: "Yuhuatai", }, }, });
1 Listen to a single refimpl data
watch(name, (newName, oldName) => { ("newName", newName); });
2 Listen to multiple refimpl data
Method 1: vue3 allows multiple watch listeners to exist
watch(name, (newValue, oldValue) => { ("new", newValue, "old", oldValue); }); watch(age, (newValue, oldValue) => { ("new", newValue, "old", oldValue); });
Method 2: Add data to the array that needs to be listened to
watch([name, age], (newValue, oldValue) => { // The returned data is an array ("new", newValue, "old", oldValue); });
3 Listen to proxy data
Notice
1. At this time, vue3 will force deep monitoring to be enabled
2. When the listening value is a proxy object, the oldValue value will have an exception, which is the same as newValue.
// Listen to proxy objectswatch(person, (newValue, oldValue) => { ("newValue", newValue, "oldValue", oldValue); });
4 Listen to a certain attribute of proxy data
You need to write the listening value into the function return form, vue3 cannot directly listen for changes in a certain attribute of the object
watch( () => , (newValue, oldValue) => { ("newValue",newValue, "oldvalue", oldValue); } );
Notice
When the attributes of the listening proxy object are complex data types, deep depth monitoring needs to be enabled
watch( () => , (newvalue, oldvalue) => { (" newvalue", newvalue, "oldvalue", oldvalue); },{ deep: true } );
5 Listen to certain properties of proxy data
watch([() => , () => ], (newValue, oldValue) => { // At this time newValue is an array ("", newValue, oldValue); });
Summarize
1. Consistent with the watch configuration in vue2
2. Two pits:
When listening to reactive defined proxy data
oldValue cannot be obtained correctly
Forced to enable deep listening (cannot be turned off)
The deep configuration item takes effect when listening for a property of the proxy object defined by the reactive
This is the article about the use of watch monitoring in VUE3. For more related content on VUE3 watch monitoring, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!