欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-22 16:56:59
效果: 代码:

效果:

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的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。