Details of watch monitoring properties in Vue

Details of watch monitoring properties in Vue

First, make sure that watch is an object and use it as such.

Key: That's the one you want to monitor;

Value: can be a function. When the thing you are monitoring changes, the function needs to be executed. This function has two parameters.

The first one is the current value (new value), the second one is the value before update (old value)

The value can also be a function name: however, the function name must be enclosed in single quotes.

The value is an object containing options: there are three options.

  • 1. The first handler : its value is a callback function. That is, the function that should be executed when a change is detected.
  • 2. The second one is deep : its value is true or false; confirm whether to monitor deeply. (Usually, you cannot listen to changes in object property values ​​during monitoring, but you can hear changes in array values.)
  • 3. The third one is immediate : its value is true or false; confirm whether to execute the handler function with the current initial value.

1.watch monitors changes in general data (numeric values, strings, Boolean values)

For example:

1. Numerical value

In data center, when we change num through the click event, we monitor its changes through watch monitoring property

<div id="app">
        <p>{{num}}</p>
        <button @click="num++">Click to add one</button>
    </div>
      let vm = new Vue({
            el:'#app',
            data:{
                num:0
            },
            watch:{
            // Current value (changed value) newval old value oldval
                num:function(newval,oldval){
                    console.log("The new value is: "+newval);
                    console.log("Old value is: "+oldval);
                }
            }
        })


When we click the button, check the console:

Note: There are two other methods in watch

 watch:{
            // Current value (changed value) newval old value oldval
                // num(newval,oldval){
                // console.log("The new value is: "+newval);
                // console.log("Old value is: "+oldval);
                // }
                num:{
                    handler(newval,oldval){
                    console.log("The new value is: "+newval);
                    console.log("Old value is: "+oldval);
                    }
                }
            }


The output results are consistent. The following examples all use the third method, which is the method with a handler .

2. Strings

<div id="app">
        <input type="text" v-model="mes">
        <p>The input content is: {{mes}}</p>
    </div>
 let vm = new Vue({
            el:'#app',
            data:{
                mes:''
            },
            watch:{
                mes:{
                    handler(newval,oldval){
                        console.log("New content: "+newval);
                        console.log("old content: "+oldval);
                    }
                }
            }
        })


When we enter content in the text box:

View the output:

3. Boolean values

<div id="app">
        <p v-show="isShow">Show and hide by modifying Boolean value</p>
        <button @click="isShow = !isShow">Click to change the Boolean value</button>
    </div>
 

let vm = new Vue({
            el:'#app',
            data:{
                isShow:true
            },
            watch:{
                isShow:{
                    handler(newval,oldval){
                        console.log("New value: "+newval);
                        console.log("old value: "+oldval);
                    }
                }
            }
        })

When the button is clicked, check the console:

2.watch monitors changes in complex data types

deep attribute: deeply monitor object changes (indicates whether to monitor deeply). When you need to monitor the changes of an object, the ordinary watch method cannot monitor the changes of the object's internal properties. At this time, the deep attribute is needed to monitor the object deeply.

1. Object

<div id="app">
        <input type="text" v-model="mes.name">
        <p>The input content is: {{mes.name}}</p>
    </div>
let vm = new Vue({
            el:'#app',
            data:{
                mes:{name:''}
            },
            watch:
                mes:{
                    // When watching the monitoring property monitoring object, the new and old values ​​are the same handler(newval){
                        console.log("New value: "+this.mes.name);
                    },
                    deep:true
                }
            }
        })


After entering something in the text box, check the console:

You can also add num to the object, control the value of num through the slider, and listen:

 <input type="range" v-model="mes.num">
 data:{
                mes:{name:'',num:''}
            },
 
watch:
                mes:{
                    // When watching the monitoring property monitoring object, the new and old values ​​are the same handler(newval){
                        console.log("num new value: "+this.mes.num);
                    },
                    deep:true
                }
            }


View the output as you slide:

2. Array

<body>
    
    <div id="app">
        <ul>
            <li v-for="(item,index) in arr">{{item}}</li>
        </ul>
        <!-- Add a button that adds a new content to the array when clicked -->
        <button @click="add()">Click to add</button>
    </div>
 
    <script src="./js/vue.js"></script>
    <script>
        let vm = new Vue({
            el:'#app',
            data:{
                arr:[1,2,3,4,5]
            },
            methods:{
                add(){
                    // Get the current maximum value of the array let cont = this.arr[this.arr.length-1];
                    // Self-increment cont++;
                    // Add an element to the last position of the array this.arr.push(cont);
                }
            },
            watch:
                arr:{
            // When monitoring an array, you don't need to monitor deeply.
                    handler(newval){
                        console.log("The new array is: "+newval);
                    }
                }
            }
        })
    </script>
</body>


After clicking Add Element, check the output:

3. Object Array

<body>
    
    <div id="app">
        <ul>
            <li v-for="item in list">
                {{item.id}}--{{item.name}}
            </li>
        </ul>
        <!-- Define the text box and add a new object to the array -->
        <input type="text" v-model="id">
        <input type="text" v-model="name">
        <button @click="add()">Add</button>
    </div>
 
    <script src="./js/vue.js"></script>
    <script>
        let vm = new Vue({
            el:'#app',
            data:{
                list:[
                    {id:1,name:"哇哈"},
                    {id:2,name:"哇哈哈"},
                    {id:3,name:"哇哈哈哈哈"}
                ],
                id:"",
                name:''
            },
            methods: {
                // Add the received input to the array add(){
                    this.list.push({id:this.id,name:this.name});
                    // Clear the contents of the text box this.id=this.name=''
                }
            },
            watch:{
                // Note: The data monitored in the watch object must be the data that already exists in the data center data // The new and old values ​​of the watch monitoring array object are equal, but when monitoring the array, deep monitoring is not required!
                list:{
                    handler(newval){
                        newval.forEach((item)=>{
                            console.log(item.name);
                        })                       
                    }
                }
            }
        })
    </script>
</body>


View the output after adding a new element:

4. Properties of object arrays

<body>
    
    <div id="app">
        <ul>
            <li v-for="x in list">
                {{x.id}}---{{x.name}} &emsp;
                <button @click="mod(x.id)">Modify</button>
            </li>
        </ul>
    </div>
 
    <script src="./js/vue.js"></script>
    <script>
        let vm = new Vue({
            el:'#app',
            data:{
                list:[
                    {id:1,name:'ww'},
                    {id:2,name:'ee'},
                    {id:3,name:'qq'}
                ],
            },
            methods: { 
                mod(id,name){
                    this.list.forEach((item)=>{
                        // Make a judgment during the traversal process. If the id you clicked is the data you are currently editing if (item.id == id) {
                            item.name = "Old Iron"
                            console.log(item);
                        }
                    })
                }
            },
            watch:
                list:{
                    handler(x,y){
                        x.forEach((element)=>{
                            console.log(element.name);
                        })
                    },
                    deep:true
                }
            }
        })
    </script>
</body>


When you click Modify, view the output:

This is the end of this article about the details of the watch monitoring properties in Vue. For more relevant content about the watch monitoring properties in Vue, 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 how to use watch to monitor data changes in mini programs
  • Detailed explanation of watch monitoring data changes in vue and each attribute in watch
  • Data changes in the vue project are monitored and processed by watch

<<:  A brief discussion on whether CSS will block page rendering

>>:  Introduction to the use of HTML element noscript

Recommend

Implementation of Nginx hot deployment

Table of contents Semaphore Nginx hot deployment ...

MySQL database transaction example tutorial

Table of contents 1. What is a transaction? 2. Th...

How to insert pictures into HTML pages and add map index examples

1. Image formats supported on the WEB: GIF: can s...

Nginx sample code for implementing dynamic and static separation

In combination with the scenario in this article,...

5 common scenarios and examples of JavaScript destructuring assignment

Table of contents Preface 1. Extract data 2. Alia...

Detailed explanation of the use of MySQL paradigm

1. Paradigm The English name of the paradigm is N...

Vue axios interceptor commonly used repeated request cancellation

introduction The previous article introduced the ...

MySQL database Load Data multiple uses

Table of contents Multiple uses of MySQL Load Dat...

MySQL stored procedure in, out and inout parameter examples and summary

Stored Procedures 1. Create a stored procedure an...

Implement a simple search engine based on MySQL

Table of contents Implementing a search engine ba...

Detailed explanation of uniapp's global variable implementation

Preface This article summarizes some implementati...