How does watch in Vue monitor an object deeply

 

Analysis: The most basic usage of watch is

export default { 
 data () { 
     return { 
         name:'张三' 
     } 
 }, 
 watch: { 
     // The name function corresponds to the data name 
     name (newValue, oldValue) { 
         
     } 
 } 
}

In the above code: there is a principle of who to listen to, who to write the name, and then the corresponding execution function. The first parameter is the latest changed value, and the second value is the last changed value. Note: In addition to monitoring data, also You can monitor 计算属性or calculate the result of a function

How to monitor the object deeply, two ways

  1. String nesting

export default { 
    data () { 
        return { 
           a: { 
               b: { 
                   c :'Zhang San' 
               } 
           } 
        } 
    }, 
    watch: { 
        //Want to monitor c At this time, the data is abc deeper. Monitor 
        "abc": function (newValue , oldValue) { 
            
        } 
    } 
}
  1. Enable deep monitoring

    export default { 
        data () { 
            return { 
               a: { 
                   b: { 
                       c :'Zhang San' 
                   } 
               } 
            } 
        }, 
        watch: { 
            a: { 
                deep: true // if deep is true, it means that deep monitoring is enabled for any object in a Data changes will trigger the handler function, 
                handler(){ 
                   // handler is a fixed writing 
                } 
            } 
        } 
    }

 

Guess you like

Origin blog.csdn.net/weixin_43837268/article/details/109273941