content
The watch in vue mainly listens to the data
数组
, yes对象
值变化
1. Several methods of watch use
(1) Monitor the change of data data through watch, when the data changes, the current value will be printed
watch: {
data(val, newval) {
console.log(val)
console.log(newval)
}
}
(2) Monitor the change of docData data through watch. When the data changes, this.change_number++ (using deep monitoring)
watch: {
data: 'changeData' // 值可以为methods的方法名
},
methods: {
changeData(curVal,oldVal){
conosle.log(curVal,oldVal)
}
}
2. Explain the immediate, handler and deep attributes in watch in detail
(1) Immediate and handler
have a feature when using watch like this, that is, when the value is bound for the first time, the monitoring function will not be executed, only when the value changes. Properties are used if we need to 最初
also execute a function when binding a value . E.g:需要
immediate
watch: {
docData: {
handler(newVal) {
this.change_number++
},
immediate: true
}
}
(2) Deep
When needed 监听一个对象的改变
, the ordinary watch method cannot monitor the change of the internal properties of 此时就需要deep属性
the object, and deeply monitor the object.
E.g:
data() {
return {
docData: {
'doc_id': 1,
'tpl_data': 'abc'
}
}
},
watch: {
docData: {
handler(newVal) {
this.change_number++
},
deep: true
}
}
Set deep: true to monitor the change of docData.doc_id. At this time, this listener will be added to all attributes of docData. 对象属性较多
At that time , the handler will be executed for each attribute value change. If 只需要监听对象中的一个属性值
, you can do the following optimization: use the form of a string to monitor object properties:
E.g:
data() {
return {
docData: {
'doc_id': 1,
'tpl_data': 'abc'
}
}
},
watch: {
'docData.doc_id': {
handler(newVal, oldVal) {
......
},
deep: true
}
}
This will only add a listener to a specific property of the object
3. Summary
数组
(One-dimensional, multi-dimensional) changes 不需要
are deeply monitored, 对象
and property changes of objects in the array are 需要deep
deeply monitored.
If you feel that the article is good, remember to pay attention, pay attention and collect it. Please correct me if there is any mistake. If you need to reprint, please indicate the source, thank you! ! !