效果:代码:<divid="app2"><label>幼儿园入学年龄(3~6):</label><inputtype="numbe
效果:
代码:
<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的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
Vue2 监听 watch