Vue2 监听属性改变watch

来源:互联网 发布:js集合和数组 编辑:程序博客网 时间:2024/06/11 15:34

效果:

  


代码:

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