效果:
代碼:
<div id="app2"> <label>幼兒園入學(xué)年齡(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); } }, //構(gòu)造器內(nèi)的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默認(rèn)true immediate指示是否立即以表達(dá)式的當(dāng)前值觸發(fā)回調(diào) </script>
以上這篇Vue2 監(jiān)聽屬性改變watch的實(shí)例代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
Copyright ? 2019- 91gzw.com 版權(quán)所有 湘ICP備2023023988號(hào)-2
違法及侵權(quán)請(qǐng)聯(lián)系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市萬商天勤律師事務(wù)所王興未律師提供法律服務(wù)