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

About VUE's compilation scope and slot scope slot issues

What are slots? The slot directive is v-slot, whi...

Vue+element implements drop-down menu with local search function example

need: The backend returns an array object, which ...

How to set up FTP server in CentOS7

FTP is mainly used for file transfer, and is gene...

Detailed explanation of the difference between chown and chmod commands in Linux

In Linux system, both chmod and chown commands ca...

How to view MySQL links and kill abnormal links

Preface: During database operation and maintenanc...

Detailed analysis of classic JavaScript recursion case questions

Table of contents What is recursion and how does ...

A super detailed Vue-Router step-by-step tutorial

Table of contents 1. router-view 2. router-link 3...

Html Select uses the selected attribute to set the default selection

Adding the attribute selected = "selected&quo...

How to filter out duplicate data when inserting large amounts of data into MySQL

Table of contents 1. Discover the problem 2. Dele...

Basic learning tutorial of table tag in HTML

Table label composition The table in HTML is comp...

Vue implements horizontal scrolling of marquee style text

This article shares the specific code for Vue to ...

Example of implementing load balancing with Nginx+SpringBoot

Introduction to Load Balancing Before introducing...

Mysql sql slow query monitoring script code example

1. Modify my.cnf #The overall effect is that both...