侦听器的应用场景:
数据变化时执行异步或开销较大的操作。
数据一旦发生了变化就 通知侦听器所绑定的方法。
1 <!-- vue 侦听器 --> 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 10 </head> 11 <body> 12 <div id='app'> 13 14 <div>姓:<input v-model="firstName"></input></div> 15 <div>名:<input v-model="lastName"></input></div> 16 <div>全名:<input v-model="fullName"></input></div> 17 18 </div> 19 20 <script> 21 var vm = new Vue ({ 22 el:'#app', 23 data:{ 24 firstName:'jim', 25 lastName:'Green', 26 fullName:'Jim Green' 27 }, 28 methods: { 29 30 }, 31 // 侦听器 32 watch:{ 33 firstName: function (value) { 34 this.fullName = value + ' ' + this.lastName 35 }, 36 lastName: function(value) { 37 this.fullName = this.firstName + ' ' + value 38 } 39 } 40 }) 41 </script> 42 </body> 43 </html>