美文网首页
Watch 选项 监控数据(21)

Watch 选项 监控数据(21)

作者: 小囧兔 | 来源:发表于2018-03-05 15:51 被阅读0次

Vue.js 提供了一个方法 watch,它用于观察Vue实例上的数据变动。对应一个对象,键是观察表达式,值是对应回调
这节课 不是很明白,只能通过例子来说明,监听温度的变化来穿衣服。

<div id="app">
   <p>今日的温度:{{wendu}}</p>
    <p>穿衣建议:{{chuanyi}}</p>
    <p>
        <button @click="rise()">升高温度</button>
        <button @click="lower()">降低温度</button>
    </p>
</div>
<script>
    var closeArr=['夹克长裙','短袖T恤','羽绒服'];
    var app=new Vue({
        el:"#app",
        data:{
            wendu:13,
            chuanyi:'夹克长裙'
        },
        methods:{
            rise:function(){
                this.wendu+=5;
            },
            lower:function(){
                this.wendu-=5;
            }
        },
        watch:{
            wendu:function(newVal,oldVal){
                if(newVal>=26){
                    this.chuanyi='短袖T恤';
                }else if(newVal<26&&newVal>=0){
                    this.chuanyi='夹克长裙'
                }else {
                    this.chuanyi='羽绒服'
                }
            }
        }
    });

二、用实例属性写watch监控
有些时候我们会用实例属性的形式来写watch监控。也就是把我们watch卸载构造器的外部,这样的好处就是降低我们程序的耦合度,使程序变的灵活。

<div id="app">
   <p>今日的温度:{{wendu}}</p>
    <p>穿衣建议:{{chuanyi}}</p>
    <p>
        <button @click="rise()">升高温度</button>
        <button @click="lower()">降低温度</button>
    </p>
</div>
<script>
    var closeArr=['夹克长裙','短袖T恤','羽绒服'];
    var app=new Vue({
        el:"#app",
        data:{
            wendu:13,
            chuanyi:'夹克长裙'
        },
        methods:{
            rise:function(){
                this.wendu+=5;
            },
            lower:function(){
                this.wendu-=5;
            }
        },
//        watch:{
//            wendu:function(newVal,oldVal){
//                if(newVal>=26){
//                    this.chuanyi='短袖T恤';
//                }else if(newVal<26&&newVal>=0){
//                    this.chuanyi='夹克长裙'
//                }else {
//                    this.chuanyi='羽绒服'
//                }
//            }
//        }
    });
  app.$watch('wendu',function(newVal,oldVal){
      if(newVal>=26){
          this.chuanyi='短袖T恤';
      }else if(newVal<26&&newVal>=0){
          this.chuanyi='夹克长裙'
      }else {
          this.chuanyi='羽绒服'
      }
  })

相关文章

网友评论

      本文标题:Watch 选项 监控数据(21)

      本文链接:https://www.haomeiwen.com/subject/htrhfftx.html