Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Computed and watch in Vue

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "how to use Computed and watch in Vue", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use Computed and watch in Vue" article.

Computedcomputed receives only one getter function

1. Getter must have a return value

2. Computed returns a read-only responsive ref object (read-only, responsive, object)

Note: when omputed receives only one getter function, it returns a read-only object, that is, its return value cannot be modified!

Getter trigger condition

1. When the computed return value is read for the first time

2. When the responsive variable bound by getter is modified

Import {ref,computed} from 'vue'const num = ref (1) / / computed returns a read-only responsive ref object computedNum//computedNum is a read-only attribute let computedNum = computed (() = > num.value + 1)

Num: {{num}}

ComputedNum: {{computedNum}}

Num++ computedNum++computed receives both getter function object and setter function object

1. The setter function object does not return a value

2. Computed returns a readable and writable responsive object

3. The setter function object has parameters, which is the return value of getter and the value of computed.

4. Modify the computed return value and trigger the execution of the setter function object, but it will not really modify the computed return value (changing the getter calculated value within the setter will change the computed return value)

Setter trigger condition

When the computed return value is modified

Example:

Import {ref, computed} from 'vue'const num = ref (1) / / getter (read only) let computedNum = computed (() = > num.value + 1) / / getter and setter (readable and writable) let computedNum2 = computed ({get: () = > num.value + 1, set: (val) = > {console.log (val)) / / modify the ref responsive variable num in setter, which will trigger the getter calculation of the associated num / / computedNum and the getter of computedNum2 simultaneously trigger num.value++}})

Num: {{num}}

ComputedNum: {{computedNum}}

ComputedNum2: {{computedNum2}}

Num++ computedNum++ computedNum2++ debug Computed

Scope of use: only development mode takes effect

The second parameter of computed: objects with onTrack and onTrigger options

OnTrack: triggered when getter is associated with responsive data.

OnTrigger: triggered when the responsive data associated with getter is modified

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);}})

Num: {{num}}

ComputedNum: {{computedNum}}

Num++watchEffect

Syntax:

Parameter 1: trigger the listening callback function, which can be passed in an onInvalidate function as an argument!

Optional parameter 2: object, including 3 optional attributes flush, onTrack, onTrigger

Immediately executes a function passed in, responsively tracks its dependencies, and reruns the function if it depends on changes.

1. It will be executed immediately (same as the immediate attribute of watch)

2. Triggered when the associated responsive data is modified

3. Code dependency is automatically perceived. Unlike watch, watchEffect actively binds listening data.

Limitations: you cannot listen to objects (but you can listen to their properties). You can only listen for responsive data similar to ref basic data types.

Execute listening immediately basic data type import {ref, watchEffect} from 'vue'const num = ref (1) / / watchEffect (() = > {console.log (' watchEffect'); num.value++}) is executed immediately)

Num: {{num}}

Num++ stop watchEffect

Implicit: automatically stops when a component is uninstalled

Explicit: return value by calling watchEffect

Const stop = watchEffect (() = > {/ *... * /}) / / explicitly stop stop () cleaning watchEffect

Syntax: watchEffect (onInvalidate= > {onInvalidate (() = > {})})

OnInvalidate is a function! Priority trigger!

Timing of onInvalidate execution:

1. When watchEffect is triggered again

2. When the component is uninstalled

Note: the onInvalidate function is not triggered when the associated responsive data is modified for the first time!

Function: clean up timer, event monitor 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, / / onInvalidate-2// watchEffect-1// watchEffect-3//2 when watchEffect is retriggered, / / onInvalidate-2//3 when the component is unloaded, / / watchEffect-1// watchEffect-3watchPostEffect and watchSyncEffect when the associated responsive data is first modified (when the component is mounted)

WatchPostEffect and watchSyncEffect are added to Vue3.2, which are watchEffect-like grammatical sugar.

Is the syntax sugar of post and sync in watchEffect optional parameter object {flush?: 'pre' |' post' | 'sync'}, and pre is the default value

Delay triggering watchPostEffect

WatchPostEffect is the syntax sugar of watchEffect optional parameter object {flush:'post'}

Postpone the trigger time of watchEffect! Triggered before component update! That is, triggering between onBeforeUpdate and onUpdated in the lifecycle

Syntax:

/ / delay triggering watchEffectwatchEffect (() = > {/ *... * /}, {flush: 'post'}) / / Vue3.2 grammatical sugar watchPostEffectwatchPostEffect (() = > {/ *... * /})

Example:

/ / Experimental watchEffect second parameter flush:'post' attribute watchEffect (() = > {console.log ("Experimental watchEffect second parameter {flush:'post'} attribute"); console.log (obj.age);}, {flush:'post'}) watchEffect (() = > {console.log ("watchEffect normal timing trigger"); console.log (obj.age) }) / / Lifecycle onUpdatedonUpdated (() = > {console.log ('onUpdated ()');}) / / Lifecycle onBeforeUpdateonBeforeUpdate (() = > {console.log ('onBeforeUpdate ()');})

When modifying obj.age, the execution result is as follows:

WatchEffect normal timing trigger

OnBeforeUpdate ()

Experimental watchEffect second parameter {flush: 'post'} attribute

OnUpdated ()

Synchronously trigger watchSyncEffect

WatchSyncEffect is the syntax sugar of watchEffect optional parameter object {flush:'sync'}

The coercive effect is always triggered synchronously! Inefficient! That is, the default watchEffect is triggered before

Syntax:

WatchEffect (() = > {/ *... * /}, {flush: 'sync'}) / / Vue3.2 grammatical sugar watchSyncEffectwatchSyncEffect (() = > {/ *... * /}) watchEffect cannot listen on the object / / assume that the property value of the object has been modified-modified obj.ageconst obj = reactive ({name:' Xiao Ming') Age: 18}) / / watchEffect cannot listen for object changes watchEffect (()) = > {console.log ('watchEffect listening for object changes') Console.log (obj);}) / / watchEffect can listen for object property changes watchEffect (() = > {console.log ('watchEffect listening object property changes'); console.log (obj.age);}) / / watch listen for object changes watch (obj, (obj) = > {console.log ('watch listening object changes'); console.log (obj);})

Summary: watchEffect is used to listen to basic data types, not objects, but object properties; watch can listen to basic data types and objects!

Watch

Syntax:

Parameter 1-listening data (in the form of single data, array, callback function with return value)

Parameter 2-callback function that triggers snooping, no return value

Optional parameter 3-object {immediate: true,deep:true}. The object contains 2 optional parameters and the effect is the same as the Vue2 parameter.

Vue3's watch is basically the same as Vue2's watch.

1. You need to specify listening data

2. Inertia, which is triggered only when the listening data changes (the immediate attribute can be set to trigger during initialization)

Monitor individual data

Parameter 1 is in the form of listening data:

1. Single basic data type

2. Callback function: the returned value is a single basic data type

/ / listen to a getter// listening data passing a callback function const state = reactive ({count: 0}) watch (() = > state.count, (count, prevCount) = > {/ *... * /}) / / listen directly to a refconst count = ref (0) watch (count, (count, prevCount) = > {/ *... * /}) listen for multiple data (incoming array) watch ([fooRef, barRef]) ([foo, bar], [prevFoo, prevBar]) = > {/ *... * /}) official document summary

The following code intercepts the official documentation, and you can see a lot of details about the parameters and return values of watch and watchEffect functions from the TS code!

Computed

Computed receives only one getter function

Getter trigger condition:

1. When the computed return value is read for the first time

2. When the responsive variable bound by getter is modified

Computed receives both getter function object and setter function object

Setter trigger condition: when the return value of computed is modified

/ / read-only function computed (getter: () = > T, debuggerOptions?: DebuggerOptions): Readonly// writable function computed (options: {get: () = > T set: (value: t) = > void}, debuggerOptions?: DebuggerOptions): Refinterface DebuggerOptions {onTrack?: (event: DebuggerEvent) = > void onTrigger?: (event: DebuggerEvent) = > void} interface DebuggerEvent {effect: ReactiveEffect target: any type: OperationTypes key: string | symbol | undefined} watchEffect

Parameter 1-triggers the listening callback function, which can be passed in an onInvalidate function as an argument!

Optional parameter 2-object with 3 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 = () = > voidwatch

Parameter 1-listening data (in the form of single data, array, callback function with return value)

Parameter 2-callback function that triggers snooping, no return value

Parameter 3-the incoming {immediate: true,deep:true} object has the same effect as the Vue2 parameter

/ / listen on single source function watch (source: WatcherSource, callback: (value: t, oldValue: t, onInvalidate: InvalidateCbRegistrator) = > void, options?: WatchOptions): StopHandle// listens on multiple sources function watch (sources: t callback: (values: MapSources, oldValues: MapSources, onInvalidate: InvalidateCbRegistrator) = > void, options?: WatchOptions): StopHandletype WatcherSource = Ref | (() = > T) type MapSources = {[K in keyof T]: t [K] extends WatcherSource? V: never} / / see the type declaration of the `watchEffect` sharing option interface WatchOptions extends WatchEffectOptions {immediate?: boolean / / default: false deep?: boolean} the above is about the article "how to use Computed and watch in Vue". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to learn more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report