Vue2 监听属性改变watch的实例代码

效果:

代码:

<div id="app2">
 <label>幼儿园入学年龄(3~6):</label><input type="number" v-model="child.age"> <button @click="older"> + </button> <button @click="younger"> - </button>
 <p v-show="hasErr">{{ errMsg }}</p>
</div>
<script>
 var app = new Vue({
  el:"#app2",
  data:{
   child:{age:2},
   hasErr:false,
   errMsg:""
  },
  methods:{
   older:function () {
    this.child.age ++;
   },
   younger:function () {
    this.child.age --;
   },
   hideErr:function () {
    var self = this;
    setTimeout(function () {
     self.hasErr = false;
    },3000);
   }
  },
  //构造器内的watch
  watch:{
   'child.age':function (newVal,oldVal) {
    if(newVal > 6){
     this.child.age = 6;
     this.errMsg = "不得大于6岁";
     this.hasErr = true;
     this.hideErr();
    }
   }
  }
 });
 
 app.$watch("child.age", function (newVal,oldVal) {
  if(newVal < 3){
   app.child.age = 3;
   app.errMsg = "不得小于3岁";
   app.hasErr = true;
   app.hideErr();
  }
 }, {deep:true, immediate:true}); //deep默认true immediate指示是否立即以表达式的当前值触发回调
 
</script>

以上这篇Vue2 监听属性改变watch的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。