<template>
<input type="text" v-model="name"/>
</template>
<script>
export default {
data(){
return{
name:' ',}}}</script>
Copy the code
Usage 1: Common usage
When a value is first bound, no listener function is executed
/ / 1.
watch: {
name(newVal,oldVal) {
// ...}},/ / 2,
watch: {
'name': function (val) {}},Copy the code
Usage 2: Execute immediately (immediate and handler)
Immediate Indicates whether to execute the handler when the watch is bound for the first time. A value of true means that the handler method is executed immediately when declared in Watch; A value of false executes handler only when the data changes, as with watch.
watch: {
name: {handler(newVal,oldVal){// ...},immediate: true}}Copy the code
Usage three: Deep monitor
When it is necessary to monitor changes of complex data types (objects), the ordinary watch method cannot monitor changes of internal properties of objects. Only data in data can monitor changes. In this case, the deep property is needed to monitor objects in depth.
dat(){
return {
person: {id: 1.name: 'salted fish'}}},watch: {
person: {
handler(newVal,oldVal) {
// ...
},
deep: true.immediate: true}}Copy the code
Setting deep: true applies this listener to all attributes of Person. If you need to listen for only one attribute value in an object, you can use string listening:
watch: {
'person.name': {
handler(newVal,oldVal) {
// ...
},
deep: true.immediate: true}}Copy the code
Changes in arrays (one-dimensional, multidimensional) do not require deep listening, while changes in properties of objects in object arrays require deep listening.