Detailed explanation of the basic usage of VUE watch listener

Detailed explanation of the basic usage of VUE watch listener

Listeners are generally used to monitor changes in data, and by default they are executed when the data changes.

The name of the monitored data is put here as the function name. This function has two parameters, one is the new value and the other is the old value.

In Vue, watch is used to respond to data changes. There are roughly three ways to use watch.

1. The following code is a simple usage of watch

<div id="app">
    <input type="text" v-model="firstName" />
</div>
 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
 <script>
var vm = new Vue({
    el:"#app",
    data:{
        firstName:"张"
    },
    watch:{         
        firstName:(newVal,oldVal){
//firstName is the name of the data you want to monitor. Use the function name you want to monitor, such as monitoring the firstName of v-model                    
//newVal: indicates the value after the change, that is, the first parameter, do not swap positions //oldVal: indicates the value before the change,
            console.log({newVal,oldVal}); // {newVal: "陈", oldVal: "张"}
        }
        //Write a monitoring function directly, and execute the function every time the cityName value changes.
        //You can also add the method name in string format directly after the monitored data: firstName: 'nameChange'
    },
    methods:{
        nameChange(){
         }
    }
})
 vm.firstName = "陈"; //Change the monitored value</script>

2. Immediate monitoring

There is a feature when using the basic usage of watch, that is, when the value is bound for the first time, the listening function will not be executed, and it will only be executed when the value changes. If we need to execute the function when the value is initially bound, we need to use the immediate attribute.

watch:
  firstName: {
    handler(newName, oldName) {
      this.fullName = newName + ' ' + this.lastName;
    },
    { immediate: true }
  }
}

The monitored data is written in object form, including the handler method and immediate. The function we wrote in the simple writing above is actually writing this handler method, which is omitted by default.

3. Handler method

<div id="app">
    <div>
        <p>Number: {{ myNumber }}</p>
        <p>Number: <input type="text" v-model.number="myNumber"></p>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
    el: '#app',
    data: {
        myNumber: 'Dawei'
    },
    watch:
        myNumber: {
            handler(newVal, oldVal) {
                console.log('newVal', newVal);
                console.log('oldVal', oldVal);
            },
            //When immediate is true, the callback function is triggered immediately; if it is false, the callback will not be executed immediately, just like the example above.
            immediate: true
          }
      }
 })
</script>
//The handler method is the specific method you need to execute in your watch

4. deep attribute

How do we monitor objects or properties in them? Then let's introduce the deep attribute. Its role is the key to solving this problem.

 <div id="root">
    <p>obj.a: {{obj.a}}</p>
    <p>obj.a: <input type="text" v-model="obj.a"></p>
</div> 
 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
 <script>
    new Vue({
        el: '#root',
        data: {
            obj: {
                 a: 123
            }
        },
        watch:
            obj: {
            handler(newName, oldName) {
                console.log(newName, oldName);
            },
            immediate: true,
            deep:true
            }
        } 
})
</script>

If the above code is not added with deep:true, it will not be executed in the console. It will only be executed for the first time and the output result will be undefined.

By default, the handler only monitors the reference changes of the obj property. It will only monitor when we assign a value to obj.

At this time, you can use deep observation. The listener will traverse down layer by layer and add this listener to all properties of the object, but this is too time-consuming.

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Solve the pitfalls of calling methods in Vue watch
  • Summary of Vue watch monitoring methods
  • Detailed explanation of watch monitoring data changes in vue and each attribute in watch
  • Triggering timing of watch listener in vue (pitfalls of watch and solutions)

<<:  CSS3 uses the transition property to achieve transition effects

>>:  How to install and persist the postgresql database in docker

Recommend

Detailed introduction to deploying k8s cluster on centos7 system

Table of contents 1 Version and planning 1.1 Vers...

Detailed tutorial on installing MySQL 5.7.20 on RedHat 6.5/CentOS 6.5

Download the rpm installation package MySQL offic...

CentOS 8 installation diagram (super detailed tutorial)

CentOS 8 is officially released! CentOS fully com...

Let’s talk about the symbol data type in ES6 in detail

Table of contents Symbol Data Type The reason why...

Detailed explanation of html download function

The new project has basically come to an end. It ...

Vue implements time countdown function

This article example shares the specific code of ...

Detailed explanation of docker nginx container startup and mounting to local

First, the structure inside the nginx container: ...

MySQL 8.0.11 installation summary tutorial diagram

Installation environment: CAT /etc/os-release Vie...

Three common ways to embed CSS in HTML documents

The following three methods are commonly used to d...

Detailed explanation of count without filter conditions in MySQL

count(*) accomplish 1. MyISAM: Stores the total n...

MySQL loop inserts tens of millions of data

1. Create a test table CREATE TABLE `mysql_genara...

JS code to achieve page switching effect

This article example shares the specific code of ...

Basic knowledge of HTML: a preliminary understanding of web pages

HTML is the abbreviation of Hypertext Markup Langu...