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>


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