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">
    <meta name="author" content="杨欣">
    <title></title>
    <style>
        html,
        body {
            margin: 0;
            padding: 0
        }
    </style>
    <script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
</head>

<body>
    <div id="app">{{obj.name}}</div>
    <script>
        let app = new Vue({
            el: "#app",
            data: {
                obj: {
                    name: 'yx'
                }
            },
            computed: {
                //1.把要监听的属性作为计算属性
                // name() {
                //     return this.obj.name
                // }
            },
            watch: {
                // name(newVal, oldVal) {
                //     console.log(newVal, oldVal)
                // }

                // 2.监听obj,加上deep
                obj: {
                    handler(newVal, oldVal) {
                        console.log(newVal, oldVal)
                    },
                    deep: true
                }
            },
        })
    </script>
</body>

</html>

  

posted @ 2019-09-17 17:51  Samsara315  阅读(274)  评论(0编辑  收藏  举报