Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:侦听属性
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>Vue监听属性</title> 6 <script src="vue.js"></script> 7 </head> 8 <body> 9 <div id="app"> 10 <input type="text" v-model="message"> 11 </div> 12 <script> 13 new Vue({ 14 el:"#app", 15 data:{ 16 message:"Hello world" 17 }, 18 watch:{ 19 message:function(){ 20 alert("你监听的message有变化了"); 21 } 22 } 23 }) 24 </script> 25 </body> 26 </html>
这样无论我增加还是删除都是有响应的
在做一个例子结束这篇博客!
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>Vue监听属性-控制颜色变化</title> 6 <script src="vue.js"></script> 7 <style> 8 #color { 9 display:inline-block; 10 100px; 11 height:100px; 12 border-radius:100%; 13 } 14 15 </style> 16 </head> 17 <body> 18 <div id="app"> 19 <div> 20 <input type="range" min="0" max="50" v-model="t"> 21 <span>{{ t }}</span> 22 </div> 23 <span id="color" :style="{backgroundColor:'rgb('+r+','+g+','+b+')'}"></span> 24 </div> 25 <script> 26 new Vue({ 27 el:"#app", 28 data: { 29 t:0, 30 r:0, 31 g:255, 32 b:255 33 }, 34 watch:{ 35 t:function(){ 36 this.r = this.t*5; 37 this.g = this.b = 255 - this.r; 38 } 39 40 } 41 42 }) 43 </script> 44 </body> 45 </html>
效果如下:
当鼠标滑动时颜色会发生变化