当前位置:主页 > 网页前端 > vue >

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

时间:2021-01-24 11:11:29 | 栏目:vue | 点击:

效果:

代码:

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

您可能感兴趣的文章:

相关文章