Vue ----watch 选项
用于 监听数据变化:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>Document</title> 8 </head> 9 <body> 10 <div id="demo"> 11 <h2>Vue-watch选项</h2> 12 <div> 13 <p>室外温度:{{tem}} `C</p> 14 <p>穿衣建议: {{dress}}</p> 15 <p><button @click="add(4)" >增加</button><button @click="reduce(4)">减少</button></p> 16 </div> 17 </div> 18 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 19 <script> 20 var dressList=["T恤","衬衫","羽绒服"]; //手动添加数据 21 var app=new Vue({ 22 el:"#demo", 23 data: { 24 tem:16, 25 dress:"衬衫" 26 }, 27 created () { 28 29 }, 30 methods: { 31 add:function(num){ 32 this.tem +=num; 33 }, 34 reduce:function(num){ 35 this.tem -=num; 36 } 37 }, 38 watch:{ 39 tem:function(newValue,oldValue){ 40 if(newValue >= 20){ 41 this.dress=dressList[0] 42 }else if(newValue < 20 && newValue > 0){ 43 this.dress =dressList[1]; 44 }else if(newValue <=0){ 45 this.dress =dressList[2]; 46 } 47 } 48 } 49 }); 50 60 </script> 61 62 <style lang="scss"> 63 #demo { 64 65 } 66 </style> 67 68 </body> 69 </html>
当使用 实例 watch事件
app.$watch('tem',function(newValue,oldValue){ if(newValue >= 20){ this.dress=dressList[0] }else if(newValue < 20 && newValue > 0){ this.dress =dressList[1]; }else if(newValue <=0){ this.dress =dressList[2]; } })