用法
观察 Vue 实例上的一个表达式或者一个函数计算结果的变化。回调函数得到的参数为新值和旧值。表达式只接受监督的键路径。对于更复杂的表达式,用一个函数取代。
模版代码:
1 2 3 4 5
| watch: { name(value) { this.newName = value; } }
|
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> </head> <body> <div id="app"> <div>大家好,我新名字是{{ newName }}</div> <input v-model="name" /> </div> <script type="text/javascript"> var vm = new Vue({ el: '#app', data() { return { name: '小明', newName: '' } }, watch: { name(value) { this.newName = value; } } }) </script> </body> </html>
|
在上面的例子中,watch 监听的都是一些简单的数据,如果我们需要监听一些比较复杂的数据,比如对象呢?这个时候我们就需要用到深度监听deep了。
深度监听
模版代码:
1 2 3 4 5 6 7 8
| watch: { childrens: { handler(value) { this.name = value.name; }, deep: true } }
|
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> </head> <body> <div id="app"> <div>大家好,我是{{ childrens.name }},今年{{ childrens.age }}岁了。</div> <input v-model="childrens.name" /> <div>我是监听器,我监听到了 {{ oldName }} </div> <script type="text/javascript"> var vm = new Vue({ el: '#app', data() { return { childrens: { name: '小明', age: 18 }, name: '', oldName: '' } }, watch: { childrens: { handler(value) { this.name = value.name; }, deep: true } } }) </script> </body> </html>
|
总结
在日常开发中基本是离不开watch的,所以大家要多敲几遍代码熟悉一下。如果想了解更多watch的用法,大家可以到官网去查看一下,这里只是列举了经常用的的方法。既然watch可以监听,那么它和我们上次提到的computed有什么区别呢?下一章我们来看一下它们之间的区别。