- Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
A, wacthEffect
- Execute immediately, without immediate
- Listen, watchEffect is executed immediately, without immediate, without passing the contents of the listen, automatically aware of code dependencies, without passing arguments, just passing a callback function that does not retrieve the previous value
- If you need to disable the listener, you can call back the listener function
const stop = watchEffect(()=>{
// console.log('num:',num.value);
// console.log('num:',str.value);
})
Copy the code
Second, the watch
- You need to manually enable the immediate function
// Specify the main listening value num
watch(num,(val,oval) = >{
// val: new value,oval: previous value
// console.log(num.value);
// console.log(val,oval);}, {// Obj immediate,deep
immediate:true// The default is to listen only when the data changes,
// It will not be executed the first time it is created. If set to true, it will be executed the first time
})
Copy the code
- Listen for the ref’s data source
- Listening to reactive data sources
-
1.1 The first method of interception
// Listen for changes in object data under the state id
watch(state,(val,oval) = >{
// console.log('id',val.id,oval);}, {immediate:true.deep:true// Enable depth monitoring to listen for changes in object property values
})
Copy the code
-
1.2 The second method of interception
/ / listen for the state. The uname
watch(() = >state.uname,(uname,p) = >{
//uname new value,p old value
console.log(uname,p); }, {immediate:true
})
Copy the code
-
1.3 Listening to multiple data sources
// Listen for multiple data (id,uname)
//()=>state.id, equivalent to //object.values(toRefs(state))
const stop = watch([() = >state.id,() = >state.uname],([id,uname],[oid,oname]) = >{
// Id is new, OID is old
console.log('id',id,oid);
// uname new,oname old
console.log('uname',uname,oname);
})
Copy the code
The last
If it is helpful to you, I hope I can give 👍 comment collection three even!
Bloggers are honest and answer questions for free ❤