Vue选项
Vue中的watch选项
watch选项是可以监控数据的变化的,根据不同的数据显示不同的效果。
例子:通过监控天气的温度变化,提出不同的穿衣建议。
如当温度大于26摄氏度时,建议穿"T恤短袖",当温度在0~26摄氏度时,建议穿“夹克长裙”,当温度小于0摄氏度时,建议穿“棉衣棉服”。
首先先定义一个穿衣建议数组:
var styleArray=['T恤短袖','夹克长裙','棉衣棉服']
增加两个点击按钮,一个升高温度,一个降低温度,以此来模拟温度的变化。
<button @click="addTemp">增加温度</button>
<button @click="cutTemp">降低温度</button>
methods:{
addTemp:function(){
this.template+=5;
},
cutTemp:function(){
this.template-=5;
}
},
在构造器内部使用watch选项时:
watch:{
template:function(newVal,oldVal){
if(newVal>=26){
this.style=styleArray[0]
}else if(newVal<26 &&newVal>0){
this.style=styleArray[1]
}else{
this.style=styleArray[2]
}
}
}
在构造器之外调用watch选项,以实例属性的形式来写watch监控
demo.$