Watch 选项 监控数据(21)

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='羽绒服'
      }
  })
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,859评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,977评论 25 708
  • 意志力实验:直面自身欲望 ,但不要付诸行动 在好时巧克力实验中 ,实验组织者告诉那些知道 “白熊 ”现象和 “反弹...
    Fly_Catkin阅读 357评论 0 0
  • 静静地坐着 与其说是倾听音乐 不如说 是倾听自己心底的声音 久违了 黑暗中的安静 安静中的心灵 让音乐在心间流淌 ...
    sweetleave阅读 118评论 0 0
  • 2017.7.24 晴 琐事记录 我给儿子洗澡,老公打开门看看我们:你们在洗澡呀,水不要太热哦,哎哟你看都红了! ...
    carol晓霞阅读 168评论 2 1