您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在Vue2 中使用watch監(jiān)聽屬性的改變,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
代碼:
<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>
上述內(nèi)容就是怎么在Vue2 中使用watch監(jiān)聽屬性的改變,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。