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

Vue3.x uses mitt.js for component communication

Table of contents Quick Start How to use Core Pri...

Web Design Experience

<br />The author used to be a novice in web ...

MySQL series: redo log, undo log and binlog detailed explanation

Implementation of transactions The redo log ensur...

How to choose the format when using binlog in MySQL

Table of contents 1. Three modes of binlog 1.Stat...

On Visual Design and Interaction Design

<br />In the entire product design process, ...

Learning Vue instructions

Table of contents 1. v-text (v-instruction name =...

Differences between this keyword in NodeJS and browsers

Preface Anyone who has learned JavaScript must be...

The order of event execution in the node event loop

Table of contents Event Loop Browser environment ...

Windows Server 2016 Standard Key activation key serial number

I would like to share the Windows Server 2016 act...

How to set up scheduled backup tasks in Linux centos

Implementation Preparation # Need to back up the ...

Organize the common knowledge points of CocosCreator

Table of contents 1. Scene loading 2. Find Node 1...

Practical record of MySQL 5.6 master-slave error reporting

1. Problem symptoms Version: MySQL 5.6, using the...