Article Directory
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 computed
can 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 watch
of 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.
❀ Expand it ❀
Different from computed
the many-to-one scenario of calculated attributes computed
, please see the previous article for the explanation of calculated attributes :
The listener watch
has two writing forms, namely:
- Vue instance internal properties
watch
- Vue instance method
vm.$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.$watch
the 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-model
commands to bind username
properties 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)
}
}
})
② methods
Method 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 methods
the 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 watch
the basic form of the listener , you can see why it is suitable for one-to-many scenarios:
① The monitoring object is a specific instance data
attribute;
The implication is that if you choose to use a listener to watch
do multiple data monitoring, then sorry, you can only monitor one by one.
For example, the previous computed
example of adding two numbers in the calculation attribute add:
data:{
num1:0,
num2:2
},
computed:{
add:function(){
return this.num1 + this.num2
}
}
watch
The 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 methods
methods;
computed
The getter
function body of the previous calculation attribute must return
end with a statement, which means that the calculation attribute computed
will eventually be attributed to one value; but in the listener, watch
there is no such limitation. You can choose to call multiple methods
methods, that is, perform multiple data operating.
computed:{
reverseMsg:function(){
return this.msg.split('').reverse().join('')
}
}
2.3 Complete form
Listener watch
complete form includes three handler
attributes: deep
, immediate
, . The previous basic form is handler
a 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
- handler -callback function
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 deep
property 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
handler
A function is a callback function that will be executed after listening to any property change in the object. It should be noted that handler
keywords 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 watch
if 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 deep
is 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 handler
function in the monitoring will not be executed . If we want to execute a handler
function 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"
}
}
})
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.$watch
It is watch
the corresponding API of the monitoring attribute . The following is a screenshot of the API introduction of the official document: I
will not introduce too much here. The usage watch
is 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:
- Call outside the instance;
- The callback function uses
function
keywords insteadhandler
; - Finally optional attributes
deep
,immediate
needs to be encapsulated into the subject;