Vue使用watch监听指定数据的变化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xukongjing1/article/details/82899765

 在Vue中,可以使用watch属性来监听data中某个属性值的变化。

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>
<body>
  <div id='app'>
    <input type="text" v-model="firstname" >+
    <input type="text" v-model="lastname" >=
    <input type="text" v-model="fullname">
  </div>
</body>
<script src="../lib/vue.js"></script>
<script>
  var vm = new Vue({
    el:'#app',
    data:{
      firstname:'',
      lastname:'',
      fullname:''
    },
    methods:{
     
    },
    //使用这个属性,可以监视 data 中指定数据的变化,然后触发这个 watch 中对应的function 处理函数
    watch:{
      firstname:function(newVal,oldVal){
        //console.log('监视到了firstname的变化');
        //this.fullname = this.firstname + "-" + this.lastname
        console.log(newVal +"---"+oldVal)
        this.fullname = newVal + "-" + this.lastname
      },
      'lastname':function(newVal){
        this.fullname = this.firstname + "-" + newVal
      }
    }
  })
</script>
</html>

猜你喜欢

转载自blog.csdn.net/xukongjing1/article/details/82899765