New usage of watch and watchEffect in Vue 3

New usage of watch and watchEffect in Vue 3

1. New usage of watch

In the optional API, watch uses

watch:{

 mood(curVal,preVal){

  console.log('cur',curVal);//Latest value console.log('pre',preVal);//Change the previous value}

}

1.1.watch usage syntax

In Composition API , when using watch , you must first import it.

The syntax is:

import { watch } from "vue"

watch(

 name ,

 ( curVal , preVal )=>{ //Business processing},

 options

)

There are three parameters:

  • name : The attribute to be listened to
  • (curVal,preVal)=>{ //業務處理} Arrow function, which is the latest value monitored and the value before this modification, and logical processing is performed here.
  • options : Configuration items, configuration of the listener, such as whether to perform deep listening.

It will not be executed when the page is first entered. When the value changes, the current latest value and the value before modification will be printed out.

Example 1 : Listening for a data

import { ref , watch } from "vue"

export default{

 setup(){

  const mood = ref("")

  //Frame listener watch(mood,(curVal,preVal)=>{

   console.log('cur',curVal);

   console.log('pre',preVal);

  },{

   //Configuration items})

  return {

   mood

  }

 }

}

watch can also monitor multiple property values. In this case, the incoming data becomes an array and the configuration items remain unchanged.

1.2. watch monitors multiple attribute values

Example 2 : Listening to multiple properties

watch([mood,target],([curMood,curTarget],[preMood,preTarget])=>{

 console.log('curMood',curMood);

 console.log('preMood',preMood);

 console.log('curTarget',curTarget);

 console.log('preTarget',preTarget);

},{

  //Configuration items}) 

1.3. watch monitor reference data type

When watch a reference data type, if you only monitor one of its properties,

The usage syntax is as follows:

watch(()=>obj.name,(curValue,preValue)=>{

 //Frame listens to a property of the reference data type},{

 //Configuration items})

The first parameter, the callback function returns the properties of the object that needs to be listened to. The following parameters are the same as above.

Example 3 : Frame listen object attribute

<template>

 <div>

  {{obj}}

  <input type="text" v-model="obj.name">

 </div>

</template>

<script>

import { ref , reactive , watch } from "vue"

export default{

 setup(){

  const obj = reactive({ name:'qq',sex:'女' })

  watch(()=>obj.name,(cur,pre)=>{

   console.log('cur',cur);

  },{ })

  return {

   obj

  }

 }

}

</script>

If we try to remove the attribute and directly monitor the entire object, we find watch seems to be invalid. At this point we need to introduce watchEffect .

2.watchEffect

watchEffect is also a frame listener and a side effect function. It will monitor all properties of the referenced data type, without having to specify a specific property. It will monitor immediately once it is run and stop monitoring when the component is uninstalled.

Example 4 : Listening Object

<template>

  <div>

    {{obj}}

    <input type="text" v-model="obj.name">

    <input type="text" v-model="obj.sex">

  </div>

</template>

<script>

import { reactive , watchEffect } from "vue"

export default{

  setup(){

    let obj = reactive({ name:'qq',sex:'女'})

    watchEffect(() => {

      console.log('name',obj.name);

      console.log('sex' , obj.sex);

    })

    return {

      obj

    }

  }

}

</script>

 

The watchEffect parameter has only one callback function. At this time, refresh the page and watchEffect will print the result.

3. The difference and connection between watch and watchEffect

watch and watchEffect are both listeners, so what is the relationship between them?

3.1. Features of watch

watch listening function can add configuration items or set it to empty. When the configuration item is empty,

The features of watch are:

  • Lazy : When running, it will not be executed immediately.
  • More specific : the properties to be monitored need to be added.
  • You can access the previous value of the property : the callback function will return the latest value and the value before the modification.
  • Configurable : You can add configuration items.

3.2.watch configuration items

The configuration items of watch can supplement the deficiencies of watch features. The configuration items are:

  • immediate : configures whether the watch property is executed immediately. When the value is true, it will be executed immediately once it is run. When the value is false , it remains lazy.
  • deep : configures whether watch is deeply monitored. When the value is true, all properties of the object can be monitored. When the value is false, more specific features must be specified on specific properties.

3.3. Features of watchEffect

The watchEffect side effect function has the following characteristics:

  • Non-lazy : Executed immediately once run.
  • More abstract : You don’t need to specify who to listen to when using it, you can use it directly in the callback function. Compared to watch it is more difficult to understand.
  • Inaccessible to previous values : Only the latest value can be accessed, but not the value before modification.

3.4. Relationship between watch and watchEffect

The first two features of watch are exactly opposite to the two features of watchEffect . watch can be modified to have watchEffect features through configuration items.

Example 5 : watch monitoring object

<template>

 <div>

  {{obj}}

  <input type="text" v-model="obj.name">

 </div>

</template>

<script>

import { ref , reactive , watch } from "vue"

export default{

 setup(){

  const obj = reactive({ name:'qq',sex:'女' })

  watch(()=>obj,(cur,pre)=>{

   console.log('cur',cur);

  },{ 

   immediate:true,

   deep:true

  })

  return {

   obj

  }

 }

}

</script>

This is the end of this article about the new usage of watch and watchEffect in vue 3. For more relevant content about watch and watchEffect in vue 3, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the usage of watch and watchEffect in VUE3
  • A brief analysis of the use of watchEffect in Vue3
  • The use and difference between vue3 watch and watchEffect
  • Do you know about watch and watchEffect of vue3?

<<:  How to distribute two buttons on the left and right sides of the same parent tag using CSS

>>:  The difference between the knowledge of front-end developers and artists in website development

Recommend

MySQL knowledge points for the second-level computer exam mysql alter command

Usage of alter command in mysql to edit table str...

A brief analysis of MySQL backup and recovery

Table of contents 1. Introduction 2. Simple defin...

Create a movable stack widget function using flutter

This post focuses on a super secret Flutter proje...

Implementation principle and configuration of MySql master-slave replication

Database read-write separation is an essential an...

Detailed explanation of virtual DOM and diff algorithm in react

The role of virtual DOM First of all, we need to ...

Share 101 MySQL debugging and optimization tips

MySQL is a powerful open source database. With th...

Improvement experience and sharing of 163 mailbox login box interactive design

I saw in the LOFTER competition that it was mentio...

React implements multi-component value transfer function through conetxt

The effect of this function is similar to vue的pro...

Summary of the pitfalls of using primary keys and rowids in MySQL

Preface We may have heard of the concept of rowid...

Win10 + Ubuntu20.04 LTS dual system boot interface beautification

Effect display The built-in boot interface is too...

React Synthetic Events Explained

Table of contents Start by clicking the input box...

MySQL partitions existing tables in the data table

Table of contents How to operate Operation proces...