current position:Home>How to use calculated and watch in Vue

How to use calculated and watch in Vue

2022-04-29 17:26:19Billion 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

Random recommended