The simple use of Vue-watch

 

 1. brief

In vue, use the watch to monitor data changes. There will be an initial value at the time for a change, time for a change of the initial value, the initial value will be recorded, but also to update the current value.

As a simple example (cm-meter and unit conversion, when the enter key is pressed, we Alert equivalent value)

<body>
    <div id="app">
        米:<input type="text" v-model="mi" @keyup.enter="btn">=
        厘米:<span>{{limi}}</span>
    </div>
</body>
<script>
    let myapp = new Vue({
        el:"#app",
        data:{
          mi:"",
          limi:""
        },
        methods:{
              btn:function(){
              this.limi = this.mi*100;
          }
        }
    })
    // Watch monitor data. Because only use the monitor when pressing the enter key, so we listen to the converted cm 
    myapp. Watch $ ( ' Limi ' , function () {
        Alert (myapp.mi + ' m ' + ' = ' + myapp.limi + ' cm ' )      
    })
</script>    

 The method and the immediate attribute 2.handler

A characteristic of the use of watch, that is, when the value of the first binding, does not perform the function monitor, only the value changes will be performed. If we need to also perform the function when the initial binding value , you need to use immediate property.

Behind the monitor data written objects forms, including handler methods and immediate, before we write the function is in fact write the handler method;

When the immediate represents the first binding watch the time, whether handler, the value is true it means that when it was declared in the watch, immediately execute handler method, value is false, and the general use of watch, like changes in data before the execution handler.

<div id="root">
    <input type="" name="" id="" value="" v-model="cityName"/>
</div>
var myapp = fenestra Vue, ({
    el: '#root',
    data: {
        cityName: 'Chengdu'
     },
   watch: {
      cityName: {
           handler(newName, oldName) {
               alert(newName)
         },
   
  immediate: true
    }
  }
})

 

Guess you like

Origin www.cnblogs.com/zengbisheng/p/11946525.html