current position:Home>How to use calculated and watch in Vue
How to use calculated and watch in Vue
2022-04-29 17:26:19【Billion cloud speed】
Vue Medium Computed And watch How to use it?
This article “Vue Medium Computed And watch How to use it? ” Most people don't quite understand the knowledge points of the article , So I made up the following summary for you , Detailed content , The steps are clear , It has certain reference value , I hope you can gain something after reading this article , Let's take a look at this article “Vue Medium Computed And watch How to use it? ” Article bar .
computed
computed Receive only one getter function
1、getter Must have return value
2、computed Return to one read-only Response type ref object ( read-only 、 Response type 、 object )
Be careful :omputed Receive only one getter Function time , The returned read-only object , That is, you can't modify its return value !
getter The trigger condition
1、computed When the return value is first read
2、getter When the bound responsive variable is modified
<script setup>import { ref,computed } from 'vue'const num = ref(1)//computed Returns a read-only response ref object computedNum//computedNum Is a read-only property let computedNum = computed(() => num.value + 1)</script><template> <p> num:{{ num }} </p> <p>computedNum:{{ computedNum }}</p> <!-- Modify the response variable num Trigger the... Bound to it computed Of getter--> <button @click="num++">num++</button> <!-- computedNum Is a read-only property --> <button @click="computedNum++">computedNum++</button></template>
computed Receive at the same time getter Function objects and setter Function object
1、setter The function object has no return value
2、computed Return to one Can read but write Responsive object
3、setter The function object has parameters , yes getter The return value of , It's also computed Value
4、 modify computed Return value , Trigger setter The function object executes , But it won't really change computed Return value (setter Internal change getter The calculated value will change computed Return value )
setter The trigger condition
computed When the return value is modified
example :
<script setup>import { ref, computed } from 'vue'const num = ref(1)//getter( read-only )let computedNum = computed(() => num.value + 1)//getter and setter ( Can read but write )let computedNum2 = computed({ get: () => num.value + 1, set: (val) => { console.log(val); //setter Revision in China ref Responsive variable num, Will trigger the associated num Of getter Calculation //computedNum and computedNum2 Of getter Trigger at the same time num.value++ }})</script><template> <p> num:{{ num }} </p> <p>computedNum:{{ computedNum }}</p> <p>computedNum2:{{ computedNum2 }}</p> <button @click="num++">num++</button> <!-- computedNum Is a read-only property , There will be a warning Write operation failed: computed value is readonly--> <button @click="computedNum++">computedNum++</button> <!-- computedNum2 Are readable and writable properties --> <button @click="computedNum2++">computedNum2++</button></template>
debugging Computed
Using range : Only development mode takes effect
computed The second parameter of : with onTrack
and onTrigger
The object of the option
onTrack
:getter relation Triggered when responsive data .onTrigger
:getter Associated responsive data Be modified Trigger when
<script setup>import { ref, computed } from 'vue'const num = ref(1)let computedNum = computed(() => num.value + 1, { onTrack: (e) => { console.log('onTrack'); console.log(e); }, onTrigger: (e) => { console.log('onTrigger'); console.log(e); }})</script><template> <p> num:{{ num }} </p> <p>computedNum:{{ computedNum }}</p> <!-- Every time num++ Will trigger onTrigger --> <button @click="num++">num++</button></template>
watchEffect
grammar :
Parameters 1: Trigger the listening callback function , The callback function can pass in a onInvalidate Function as parameter !
Optional parameters 2: object , contain 3 Two optional properties flush、onTrack、onTrigger
Execute now A function passed in , At the same time, it is responsive to trace its dependencies , And rerun the function when its dependency changes .
1、 It will be executed immediately ( and watch Of immediate Properties have the same effect )
2、 Associated responsive data Be modified Trigger when
3、 Automatically aware of code dependencies , and watch Dissimilarity ,watchEffect Will actively bind and monitor data
limitations : Cannot listen to objects ( But you can listen to the properties of the object ), Can only listen to things like ref Responsive data of basic data type
Execute now Listen to basic data types
<script setup>import { ref, watchEffect } from 'vue'const num = ref(1)// It will be executed immediately watchEffect(() => { console.log('watchEffect'); num.value++})</script><template> <p>num: {{ num }}</p> <button @click="num++">num++</button></template>
stop it watchEffect
Implicit : Automatically stop when components are unloaded
Explicit : call watchEffect
Return value
const stop = watchEffect(() => { /* ... */})// Explicit stop stop()
clear watchEffect
grammar : watchEffect( onInvalidate=>{ onInvalidate(()=>{ }) })
onInvalidate It's a function ! Priority trigger !
onInvalidate Execution opportunity :
1、watchEffect When triggered again
2、 When the component is uninstalled
Be careful : Associated responsive data First modified It doesn't trigger onInvalidate function !
effect : Clear timer 、 Event monitoring removeEventListener ...
import { ref, watchEffect } from 'vue'const num = ref(1)watchEffect((onInvalidate ) => { console.log('watchEffect-1'); num.value++ onInvalidate (()=>{ console.log('onInvalidate-2'); }) console.log('watchEffect-3');})//1、watchEffect When triggered again // onInvalidate-2// watchEffect-1// watchEffect-3//2、 When the component is uninstalled // onInvalidate-2//3、 The associated responsive data is modified for the first time ( When the component is mounted )// watchEffect-1// watchEffect-3
watchPostEffect and watchSyncEffect
watchPostEffect
and watchSyncEffect
stay Vue3.2 newly added , yes watchEffect Something like grammar sugar ,
yes watchEffect
Optional parameter object { flush?: 'pre' | 'post' | 'sync'}
in post and sync The grammar sugar of ,pre Is the default value
Delay triggering watchPostEffect
watchPostEffect
yes watchEffect Optional parameter object {flush:'post'}
The grammar sugar of
delay watchEffect trigger ! Triggered before component update ! That is, in the life cycle onBeforeUpdate
and onUpdated
Trigger between
grammar :
// Delay triggering watchEffectwatchEffect( () => { /* ... */ }, { flush: 'post' })//Vue3.2 Grammatical sugar watchPostEffectwatchPostEffect(()=>{ /* ... */})
example :
// experiment watchEffect The second parameter flush: 'post' attribute watchEffect(() => { console.log(" experiment watchEffect The second parameter {flush: 'post'} attribute "); console.log(obj.age);},{ flush:'post' })watchEffect(() => { console.log("watchEffect Normal timing triggers "); console.log(obj.age);})// Life cycle onUpdatedonUpdated(()=>{ console.log('onUpdated()'); })// Life cycle onBeforeUpdateonBeforeUpdate(()=>{ console.log('onBeforeUpdate()');})
modify obj.age
when , Execution results :
watchEffect Normal timing triggers
onBeforeUpdate()
experiment watchEffect The second parameter {flush: 'post'} attribute
onUpdated()
Synchronous trigger watchSyncEffect
watchSyncEffect
yes watchEffect Optional parameter object {flush:'sync'}
The grammar sugar of
The coercive effect is always Synchronous trigger ! Low efficiency ! That's the default watchEffect Trigger before
grammar :
watchEffect( () => { /* ... */}, { flush: 'sync' })//Vue3.2 Grammatical sugar watchSyncEffectwatchSyncEffect(()=>{ /* ... */})
watchEffect Cannot listen to objects
// Suppose you modify the attribute value of the object - Revised obj.ageconst obj = reactive({ name: ' Xiao Ming ', age: 18 })//watchEffect Cannot listen for object changes watchEffect(() => { console.log('watchEffect Listen for object changes '); console.log(obj);})//watchEffect You can listen for changes in object properties watchEffect(() => { console.log('watchEffect Listen for changes in object properties '); console.log(obj.age);})//watch Listen for object changes watch(obj, (obj) => { console.log('watch Listen for object changes '); console.log(obj);})
summary :watchEffect
Used to monitor basic data types , Cannot listen to objects , But it can listen to the properties of the object ;watch Can listen to basic data types and objects !
watch
grammar :
Parameters 1- Monitored data ( form : Single data 、 Array 、 Callback function with return value )
Parameters 2- Callback function that triggers listening , No return value
Optional parameters 3- object
{immediate: true,deep:true}
, Object contains 2 Two optional parameters and Vue2 The parameter effect is consistent
Vue3 Of watch and Vue2 Of watch It's basically the same
1、 You need to specify the listening data
2、 inert , Triggered only when the monitored data changes (immediate Property can be set to trigger at initialization )
Monitor single data
Parameters 1 The form of monitored data :
1、 Single basic data type ;
2、 Callback function : The return value is a single basic data type ;
// Listen for one getter// The callback of the incoming function returns a value const state = reactive({ count: 0 })watch( () => state.count, (count, prevCount) => { /* ... */ })// Listen directly to a refconst count = ref(0)watch(count, (count, prevCount) => { /* ... */})
Listen to multiple data ( Pass in array )
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => { /* ... */})
Official document summary
The following code intercepts the official document , from TS The code can see a lot about watch and watchEffect Details of function parameters and return values !
computed
computed
Receive only one getter function
getter
The trigger condition :
1、computed When the return value is first read
2、getter When the bound responsive variable is modified
computed
Receive at the same time getter Function objects and setter Function object
setter
The trigger condition :computed When the return value is modified
// read-only function computed<T>( getter: () => T, debuggerOptions?: DebuggerOptions): Readonly<Ref<Readonly<T>>>// Writable function computed<T>( options: { get: () => T set: (value: T) => void }, debuggerOptions?: DebuggerOptions): Ref<T>interface DebuggerOptions { onTrack?: (event: DebuggerEvent) => void onTrigger?: (event: DebuggerEvent) => void}interface DebuggerEvent { effect: ReactiveEffect target: any type: OperationTypes key: string | symbol | undefined}
watchEffect
Parameters 1- Trigger the listening callback function , The callback function can pass in a onInvalidate Function as parameter !
Optional parameters 2- object , contain 3 Two optional properties flush、onTrack、onTrigger
function watchEffect( effect: (onInvalidate: InvalidateCbRegistrator) => void, options?: WatchEffectOptions): StopHandleinterface WatchEffectOptions { flush?: 'pre' | 'post' | 'sync' // Default :'pre' onTrack?: (event: DebuggerEvent) => void onTrigger?: (event: DebuggerEvent) => void}interface DebuggerEvent { effect: ReactiveEffect target: any type: OperationTypes key: string | symbol | undefined}type InvalidateCbRegistrator = (invalidate: () => void) => voidtype StopHandle = () => void
watch
Parameters 1- Monitored data ( form : Single data 、 Array 、 Callback function with return value )
Parameters 2- Callback function that triggers listening , No return value
Parameters 3- Pass in
{immediate: true,deep:true}
Objects and Vue2 The parameter effect is consistent
// Listen to a single source function watch<T>( source: WatcherSource<T>, callback: ( value: T, oldValue: T, onInvalidate: InvalidateCbRegistrator ) => void, options?: WatchOptions): StopHandle// Listen to multiple sources function watch<T extends WatcherSource<unknown>[]>( sources: T callback: ( values: MapSources<T>, oldValues: MapSources<T>, onInvalidate: InvalidateCbRegistrator ) => void, options? : WatchOptions): StopHandletype WatcherSource<T> = Ref<T> | (() => T)type MapSources<T> = { [K in keyof T]: T[K] extends WatcherSource<infer V> ? V : never}// See `watchEffect` Type declaration of sharing options interface WatchOptions extends WatchEffectOptions { immediate?: boolean // Default :false deep?: boolean}
That's about “Vue Medium Computed And watch How to use it? ” The content of this article , I believe we all have a certain understanding , I hope the content shared by Xiaobian will be helpful to you , If you want to know more about it , Please pay attention to the Yisu cloud industry information channel .
copyright notice
author[Billion cloud speed],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291539467208.html
The sidebar is recommended
- 07 Chrome browser captures hover element style
- WebGIS development training (ArcGIS API for JavaScript)
- Solution to the blank page of the project created by create react app after packaging
- 19. Html2canvas implements ArcGIS API for JavaScript 4 X screenshot function
- Introduction to JavaScript API for ArcGIS 13
- Development of ArcGIS API for JavaScript under mainstream front-end framework
- Nginx learning notes
- Less learning notes tutorial
- Vue2 cannot get the value in props in the data of the child component, or it is always the default value (the value of the parent component comes from asynchrony)
- LeetCode 217. Determine whether there are duplicate elements in the array
guess what you like
I'll write a website collection station myself. Do you think it's ok? [HTML + CSS + JS] Tan Zi
Front end browser debugging tips
Application of anti chattering and throttling in JavaScript
How to create JavaScript custom events
Several ways of hiding elements in CSS
node. Js-3 step out the use of a server and express package
CSS matrix function
Fastapi series - synchronous and asynchronous mutual conversion processing practice
How to extend the functionality of Axios without interceptors
Read pseudo classes and pseudo elements
Random recommended
- About node JS server related concepts
- Access control module (2)
- About virtual lists
- Developing figma plug-in using Vue 3 + vite
- Learn more about the garbage collection engine of chrome V8 JavaScript engine
- Vue3 uses vite instead of webpack
- How to upload applet code through node? Just take a look
- Using H5 video tag in Vue to play local video in pop-up window
- What is the difference between classes in Es5 and ES6?
- [Vue] play with the slot
- [Part 4 of front-end deployment] using docker to build cache and multi-stage construction to optimize single page applications
- Vue2 simple use of vant (based on Vue CLI)
- node. JS server
- React uses concurrent mode. When the rendering phase exceeds the time slice, high priority tasks jump the queue. How will the lanes on the fiber of the previous task be solved
- Vuecli2 multi page, how to remove HTML suffix
- Vue router dynamically modifies routing parameters
- How to use webpack or configure quasar after context isolation is turned on by electron?
- Vue3 how do parent components call child component methods
- Es learning notes (I): http request
- 【Java WEB】AJAX
- Java project: nursing home management system (java + springboot + thymeleaf + HTML + JS + MySQL)
- Java project: drug management system (java + springboot + HTML + layui + bootstrap + seals + MySQL)
- Java project: agricultural material management system (java + springboot + easyUI + HTML + Maven + MySQL)
- How do Vue, native JS and jQuery feel about development
- The Ajax backend accepts post data and writes it directly to the database
- Java project: agricultural material management system (java + springboot + easyUI + HTML + Maven + MySQL)
- Brother Lao Yu takes you to play with esp32:14 and personally make a two-way wireless remote control (I)
- How to create JavaScript custom events
- A king's time, I learned nginx
- Vue quick start (with actual small items: Notepad, weather forecast, music player)
- Vue: convert user input to numeric type
- - Status code: 404 for http://mirrors.cloud.aliyuncs.com/centos/8/AppStream/x86_64/os/repodata/repom
- vue. config. Understanding of agent in JS
- After the node is successfully installed, CMD can be executed, but the compiler webstorm runs NPM install and prompts that there is no solution to this command
- How to develop and deploy front-end code in large companies
- Vue assigns permissions to buttons through instructions
- [development diary from 22 years to April] Vue problems encountered in actual projects and their solutions
- [methodology 1] CSS development skills - global style setting and local style
- vue3. 0 dynamically bind and obtain DOM through ref;
- How to use HTML for touch event in mobile terminal