1. 程式人生 > >vue數據監控$set和$delete

vue數據監控$set和$delete

vue $set $delete

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>監控數據的變化</title> </head> <script type="text/javascript" src="js/vue.js" ></script> <body> <div id="div1"> <button @click="doUpdate">修改屬性</button> <button @click="doAdd">添加屬性</button> <button @click="doDelete">刪除屬性</button> <hr> <h2>{{user.name}}</h2> <h2>{{user.age}}</h2> </div> </body> <script> let vm = new Vue({ el: "#div1", data:{ user:{ id:1, name:'John', } }, methods:{ doUpdate(){ this.user.name = 'Tom'; }, doAdd(){ //this.user.age = 18; //通過普通方式為對象添加屬性時vue無法實時監視到 //this.$set(this.user,'age',23); //可以實時監控更新信息 if (this.user.age) { this.user.age++; }else{ Vue.set(this.user,'age',23); //第二種方式 } }, doDelete(){ if (this.user.age) { Vue.delete(this.user,'age'); } } } }); </script> </html>


vue數據監控$set和$delete