[Vue Family Bucket · Vue (6)] The second monitoring mechanism in the Vue framework-listener watch

In the previous article, we introduced the calculation properties in the Vue framework in detail computed. We said that it is commonly used for data monitoring, such as the typical many-to-one situation-multiple data monitoring and deep monitoring.

1. Watch application scenarios

But this does not mean that the computational properties computedcan be competent for all monitoring scenarios. In fact, there is a more general and orthodox monitoring method in the Vue framework-the listener watch. In theory, he can complete all monitoring work.

The monitoring watchof the listener is suitable for one-to-many scenarios, that is, the change of one data in a certain component will affect multiple other data.

Insert picture description here


❀ Expand it ❀

Different from computedthe many-to-one scenario of calculated attributes computed, please see the previous article for the explanation of calculated attributes :

[Vue study notes · Basics (5)] One of the monitoring mechanisms in the Vue framework-calculated attributes


The listener watchhas two writing forms, namely:

  • Vue instance internal propertieswatch
  • Vue instance methodvm.$watch

These two writing methods are essentially equivalent, and the required parameters are exactly the same. The only difference is the format difference caused by the different writing positions. Therefore, the following explanation will focus on the internal attributewatch form of the Vue instance as an example, and vm.$watchthe corresponding equivalent form will be given in the later part, which can be compared and selected.

2. Vue instance internal attributes watch

2.1 Basic form

  • watchObject (monitoring object-attributes in data (Number / String / Boolean / Array))
  • callback -callback function
    • newVal (not required) -the new value after the change (single- select this option)
    • oldVal (not required) -the old value before the change
new Vue({
    
    
    el:"#app",
    data:{
    
    
        watchObject:''
    },
    watch:{
    
    
        watchObject:function(newVal,oldVal){
    
    
        // something...
        }
    }
})

Look at a few simple examples:

① Get the value before and after the change:

For example, we add an input box to the page and use v-modelcommands to bind usernameproperties in two directions . We want to monitor the input of the input box: every time a character is input, the value before and after this input is printed on the console.

<div id="app">
    <input type="text" v-model="userName">
</div>
let vm = new Vue({
    
    
    el:"#app",
    data:{
    
    
        username:''
    },
    watch:{
    
    
        username:function(newName,oldName){
    
    
            console.log(newName,oldName)
        }
    }
})

Insert picture description here
methodsMethod in call :

According to different actual needs, we can also choose different parameter configurations. For example, get the value after the current change and call methodsthe method as a parameter func:

new Vue({
    
    
    el:"#app",
    data:{
    
    
        watchObject:''
    },
    watch:{
    
    
        watchObject:function(val){
    
    
            this.func(val)
        }
    },
    methods:{
    
    
        func:function(val){
    
    
            console.log(val)
        }
    }
})

It should be noted that the callback function can also receive only one parameter-the default is the changed value.

2.2 One-to-many realization principle

Carefully analyze watchthe basic form of the listener , you can see why it is suitable for one-to-many scenarios:

① The monitoring object is a specific instance dataattribute;

The implication is that if you choose to use a listener to watchdo multiple data monitoring, then sorry, you can only monitor one by one.
For example, the previous computedexample of adding two numbers in the calculation attribute add:

data:{
    
    
    num1:0,
    num2:2
},
computed:{
    
    
    add:function(){
    
    
        return this.num1 + this.num2
    }
}

watchThe version of the listener (the degree of complexity is obvious):

data:{
    
    
    num1:0,
    num2:2,
    result:2
},
watch:{
    
    
    num1:function(val){
    
    
        this.result = val + this.num2
    },
    num2:function(val){
    
    
        this.result = val + this.num1
    }
}

② The callback function body can choose to call multiple methodsmethods;

computedThe getterfunction body of the previous calculation attribute must returnend with a statement, which means that the calculation attribute computedwill eventually be attributed to one value; but in the listener, watchthere is no such limitation. You can choose to call multiple methodsmethods, that is, perform multiple data operating.

computed:{
    
    
    reverseMsg:function(){
    
    
        return this.msg.split('').reverse().join('')
    }
}

2.3 Complete form

Listener watchcomplete form includes three handlerattributes: deep, immediate, . The previous basic form is handlera shorthand form that only sets the complete form of the function.
The explanation of each attribute is as follows:

  • watchObject (monitoring object-attributes in data (Number / String / Boolean / Array / Object ))
    • handler -callback function
      • newVal (not required) -the new value after the change (single- select this option)
      • oldVal (not required) -the old value before the change
    • deep (not required) -whether to enable deep monitoring
    • immediate (not required)-whether the handler function is also executed in the data binding phase
new Vue({
    
    
    el:"#app",
    data:{
    
    
        watchObject:''
    },
    watch:{
    
    
        watchObject:{
    
    
            handler:function(newVal,oldVal){
    
    
                // something...
            },
            deep:true,
            immediate:true
        }
    }
})

2.3.1 watchObject monitor object

I don’t know if you have noticed. This time I added a new object to the list of monitoring objects Object, which means that the basic form mentioned before cannot be used to monitor the internal properties of the object. Because the deepproperty defaults to this false, we need to use the complete writing method to manually turn on deep monitoring.

For example, the following listening method will be invalid:

new Vue({
    
    
    el:"#app",
    data:{
    
    
        Obj:{
    
    
            username:''
        }
    },
    watch:{
    
    
        Obj:function(newVal,oldVal){
    
    
            console.log(newVal)
        }
    }
})

2.3.2 handler function

handlerA function is a callback function that will be executed after listening to any property change in the object. It should be noted that handlerkeywords must be used here , not the name of a custom function.

2.3.3 deep monitoring properties

As mentioned before computed, the default in the calculated properties is in-depth monitoring, and watchif you want to complete the in-depth monitoring of the internal properties of the object in the listener, you need to manually set it deep:true. For example, the example in 2.3.1 can be written like this:

new Vue({
    
    
    el:"#app",
    data:{
    
    
        Obj:{
    
    
            username:''
        }
    },
    watch:{
    
    
        obj:{
    
    
            handler:function(newVal,oldVal){
    
    
                console.log(newVal)
            },
            deep:true
        }
    }
})

Of course, it deepis also very broad not to use attributes: when setting up the listening object, use the key path (click the access symbol to select the internal attributes of the object) . For example, the equivalent form of the above example is:

// 完整形式
watch:{
    
    
    obj.username:{
    
    
        handler:function(newVal,oldVal){
    
    
            console.log(newVal)
        }
    }
}
// 基础形式
watch:{
    
    
    obj.username:function(newVal,oldVal){
    
    
        console.log(newVal)
    }
}

2.3.4 immediate immediate execution attribute

We all know that the principle of monitoring is to perform certain operations after discovering that the monitoring object has changed. So in the stage where the monitoring is not triggered, such as the data binding stage, the handlerfunction in the monitoring will not be executed . If we want to execute a handlerfunction in the data binding phase at this time, we need to setimmediate:true

For example, common data initialization operations (initialization function is called in the data binding phase):

<div id="app">
    {
    
    {
    
    Obj}}<br>
    <input type="text" v-model="Obj.username">
</div>
new Vue({
    
    
    el:"#app",
    data:{
    
    
        Obj:{
    
    
            username:''
        }
    },
    watch:{
    
    
        obj:{
    
    
            handler:function(){
    
    
                // 属性值为空时调用初始化函数
                if(!this.Obj.username){
    
    this.initFunc()} 
            },
            deep:true,
            immediate:true
        }
    },
    methods:{
    
    
        initFunc:function(){
    
    
            this.Obj.username = "zevin"
        }
    }
})

Insert picture description here

3. Vue instance method vm.$watch

The Vue framework also provides us with rich APIs, and many properties and methods in Vue instances have corresponding APIs. Attach the official API document:

Vue official API document address

vm.$watchIt is watchthe corresponding API of the monitoring attribute . The following is a screenshot of the API introduction of the official document: I
Insert picture description here
will not introduce too much here. The usage watchis the same as the previous monitoring attribute , but the writing format is different. Here is a brief list of the corresponding basic and complete forms:

3.1 Basic form

  • watchObject (monitoring object-attributes in data (Number / String / Boolean / Array))
  • callback -callback function
    • newVal (not required) -the new value after the change (single- select this option)
    • oldVal (not required) -the old value before the change
vm.$watch(watchObject, function (newVal, oldVal) {
    
    
  // something
})

3.2 Complete form

  • watchObject (monitoring object-attributes in data (Number / String / Boolean / Array / Object ))
  • callback -callback function
    • newVal (not required) -the new value after the change (single- select this option)
    • oldVal (not required) -the old value before the change
  • options -optional attributes (object)
    • deep (not required) -whether to enable deep monitoring
    • immediate (not required)-whether the handler function is also executed in the data binding phase
 vm.$watch(watchObject,function () {
    
    
      doSomething()
  },
  {
    
     
      deep:true,
      immediate: true
   }
)

The differences that need to be noted are:

  1. Call outside the instance;
  2. The callback function uses functionkeywords instead handler;
  3. Finally optional attributes deep, immediateneeds to be encapsulated into the subject;

Guess you like

Origin blog.csdn.net/JZevin/article/details/108469140