watch监听指定数据变化

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

watch监听指定数据变化

北海之灵   2022-05-28 我要评论

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

 在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>

vue watch监听多个值

用computed定义一个address对象吧,然后再去watch addres

data() {
  return {
    check: false,
    sign_img: "",
    submit_flag: false'
  }
},
computed: {
  btnObj() {
    const { sign_img, check } = this
    return {
      sign_img,
      check
    }
  }
},
watch: {
  btnObj: {
    handler: function(newVal,oldVal) {
      if(!!this.sign_img && this.check){
        this.submit_flag = true
        this.sign_flag = '1'
      }else{
        this.submit_flag = false
        this.sign_flag = '0'
      }
    },
    deep: true,
    immediate: true
  }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们