watch 监听器

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <div id="app">
        <h1>{{name}}</h1>
        <h1>{{age}}</h1>
        <input type="text" v-model="remark">
    </div>

    <script src="./vue.js"></script>
    <script>

        new Vue({
            data: {
                name: '赵胤祯',
                age: 60,
                gender: '男',
                contact: {
                    email: '[email protected]',
                    phone: '18924367819'
                },
                remark: '暂无'
            },
            methods: {
                onAgeChange: function (newAge, oldAge) {
                    console.log(newAge, oldAge)
                }
            },
            watch: {
                // 监听 name 属性的变化
                name: function (newName, oldName) {
                    console.log(newName, oldName)
                },
                // 当 data 选项中 age 属性的值变化时,执行 methods 选项中 onAgeChange 方法
                age: 'onAgeChange',
                // 当 data 选项中 contact 属性的值变化时,执行对应的处理方法
                // 注意:contact 对象中属性的值发生变化时并不会触发该方法,例如,contact.phone = '110'
                // contact: function (newContact, oldContact) {
                //     console.log(newContact, oldContact)
                // },
                // 当 contact 对象中 phone 属性的值发生变化时,执行该方法,
                // 注意:email 属性变化时,并不会触发该方法
                // 'contact.phone': function (newPhone, oldPhone) {
                //     console.log(newPhone, oldPhone)
                // },
                // 监听 contact 对象中所有属性的变化,
                // 注意,由于 newValue 和 oldValue 指向同一个对象(contact),
                // 因此 newValue 和 oldVallue 中的值都是相同的。
                contact: {
                    handler: function (newValue, oldValue) {
                        console.log(newValue.email, oldValue.email)
                        console.log(newValue.phone, oldValue.phone)
                    },
                    deep: true // 表示深度监视,不仅监视 contact 属性值的变化,还是会监视 contact 内的属性值的变化。
                },
                gender: {
                    handler: function (newGender, oldGender) {
                        console.log(newGender, oldGender)
                    },
                    // 如果你想让处理方法在监听开始时执行一次,可以设置以下属性
                    // 也就是或,该回调将会在侦听开始之后被立即调用
                    immediate: true
                },
                // 当 remark 属性值发生变化时,数组中的处理方法都会执行
                remark: [function (newRemark, oldRemark) {
                    console.log('remark handler1', newRemark, oldRemark)
                }, function (newRemark, oldRemark) {
                    console.log('remark handler2', newRemark, oldRemark)
                }]
            }
        }).$mount('#app')

    </script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/wszzj/p/12291872.html