Vue中的$watch监控数据

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>监控数据的变化</title>
    </head>
    <script type="text/javascript" src="js/vue.js" ></script>
    <body>
        <div id="div1">
            <input type="text" v-model="name">
            <h2>{{name}}</h2>
            <hr>
            <input type="text" v-model="age">
            <h2>{{age}}</h2>
            <input type="text" v-model="user.age">
            <h2>{{user.age}}</h2>
        </div>
    </body>
    <script>
        let vm = new Vue({
            el: "#div1",
            data:{
                name:'Tom',
                age:18,
                user:{
                    id:1,
                    age:20
                }
            },
            watch:{
                //方式一:监控vue实例的数据
                age:(newValue,oldValue) => {
                    console.log('name的newValue值为:'+newValue+',旧值为:'+oldValue);
                },
                user:{
                    handler:(newValue,oldValue) => {
                        console.log('age的newValue值为:'+newValue.age+',旧值为:'+oldValue.age);
                        //原来的旧值已经看不见了,只能看到新的值
                    },
                    deep: true //深度监视,当对象中的属性发生变化时会被监控
                }
            }
        });
        //方式二:监控vue实例的数据
        vm.$watch('name',function(newValue,oldValue){
                console.log('name的newValue值为:'+newValue+',旧值为:'+oldValue);
            });

    </script>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章