Vue选项之watch侦听器

侦听器:在数据变化的监控经常使用.

一.看一个监控变化的案例

我们可以先看一个简单的数据变化监控的例子,例如天气预报的穿衣指数,它主要是根据温度来进行提示的,温度大于26度时,我们建议穿T恤短袖,温度小于26度大于0度时,我们建议穿夹克长裙,温度小于0度时我们建议穿棉衣羽绒服,下面来看一下实现代码:

<body>
    <div id="app">
       <p>今日温度:{{deg}}</p> 
       <p>穿衣建议:{{clothes}}</p>
       <button @click="add">添加温度</button> <button @click="reduce">减少温度</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
      

      let app = new Vue({
        el: '#app',
        data:{
            deg:20,
            clothes:"夹克"
        },
        methods:{
            add:function(){
                this.deg+=5;
            },
            reduce(){
                this.deg-=5;
            }
        },
        watch: {
            deg:function(newValue,oldValue,){
               if(newValue>=26){
                   this.clothes="T恤"
               }else if(newValue<26&&newValue>=0){
                this.clothes="夹克"
               }else{
                this.clothes="棉袄"
               }

                
            }
        },
       
      })
    </script>
  </body>

实现效果:
在这里插入图片描述

二.用实例属性来写watch监控(新颖的写法,使代码更灵活)

实际就是把我们的watch抽离出来,放在vue构造器的下面,这样的好处是时代码更加灵活,
格式:app.$watch(‘侦听数据’,function(newVal,oldVal){})
操作如下:

<body>
    <div id="app">
      <p>今日温度:{{ deg }}</p>
      <p>穿衣建议:{{ clothes }}</p>
      <button @click="add">添加温度</button>
      <button @click="reduce">减少温度</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
      let app = new Vue({
        el: '#app',
        data: {
          deg: 20,
          clothes: '夹克'
        },
        methods: {
          add: function() {
            this.deg += 5
          },
          reduce() {
            this.deg -= 5
          }
        }
      })
      app.$watch('deg', function(newValue, oldValue) {
        if (newValue >= 26) {
          this.clothes = 'T恤'
        } else if (newValue < 26 && newValue >= 0) {
          this.clothes = '夹克'
        } else {
          this.clothes = '棉袄'
        }
      })


    </script>
  </body>

实现效果跟原来一致.

猜你喜欢

转载自blog.csdn.net/xiaodi520520/article/details/88813384