vue watch监听,handler、immediate和deep属性用法

Vue.js提供了一个方法watch,用于观察Vue实例上的数据变更。javascript

用法:
  当title值变化的时候,watch才会执行
  <div>
        <p>title:<input type='text' v-model='title' /></p>
  </div>
  <script type='text/javascript'>
  new Vue({
        el:'#app',
        data:{
              title:'监听'
        },
        watch:{
              title(newVal,oldVal){
                    //      newVal打印的就是监听到变化以后的title的值
                    console.log(newVal)
              }
        }
  })   
  </script>
  handler方法和immediate属性:
  当咱们想让值最初始的时候就执行watch,就会用到handler和immediate
  watch:{
        title:{
              handler(newVal,oldName){
                    console.log(newVal)
              },
              //  设置为true表明在watch里生明了title这个方法以后当即执行handler方法,若是设置为false,效果和上边例子同样
              immediate:true,
        }
  }
  deep属性:深度监听,用于对象或者数组对象的监听
   <div>
        <p>title:<input type='text' v-model='title.titleOne' /></p>
  </div>
  <script type='text/javascript'>
  new Vue({
        el:'#app',
        data:{
              title:{
                    titleOne:'deep监听',
                    titleTwo:'hero-see'
              },
              arr:[{name:'小明',age:'18'},{name:'小红',age:'16'}]
        },
        watch:{
              //对象深度监听
               //方式一
              title:{
                    handler:function(newObj,oldObj){
                          console.log(newObj.titleOne)
                    },
                    //对象内部属性监听,也叫深度监听
                    deep:true
              },
               //方式二,直接监听对象内部的某个值,键路径必须加上引号
              "title.titleOne":{
                    handler:function(newVal,oldVal){
                          console.log(newVal)
                    },
                    //对象内部属性监听,也叫深度监听
                    deep:true
              },
              //数组对象深度监听
              arr:{
                    handler(val){
                          console.log(val)
                    },
                    //数组对象监听需加上deep属性,表明递归监听
                    deep:true
              }

        }
  })   
  </script>
相关文章
相关标签/搜索