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 accidental deletion of data solution and kill statement principle

mysql accidentally deleted data Using the delete ...

SQL Server Comment Shortcut Key Operation

Batch comments in SQL Server Batch Annotation Ctr...

Detailed tutorial on installing CentOS, JDK and Hadoop on VirtualBox

Table of contents 1. Prerequisites 1.1 Supported ...

How to use node scaffolding to build a server to implement token verification

content Use scaffolding to quickly build a node p...

Windows 10 is too difficult to use. How to customize your Ubuntu?

Author | Editor Awen | Produced by Tu Min | CSDN ...

Why is the disk space still occupied after deleting table data in MySQL?

Table of contents 1. Mysql data structure 2. The ...

Common problems and solutions during MySQL MGR construction

Table of contents 01 Common Faults 1 02 Common Fa...

A possible bug when MySQL executes the sum function on the window function

When using MySql's window function to collect...

hr horizontal line style example code

Copy code The code is as follows: <hr style=&q...

Mobile front-end adaptation solution (summary)

I searched online and found that many interviews ...

Pure HTML and CSS to achieve JD carousel effect

The JD carousel was implemented using pure HTML a...

Comparison of several examples of insertion efficiency in Mysql

Preface Recently, due to work needs, I need to in...

The most commonly used HTML tags to create web pages

1. Optimization of commonly used HTML tags HTML s...

Deleting two images with the same id in docker

When I created a Docker container today, I accide...