vue : watch、computed、以及對象數組
阿新 • • 發佈:2019-01-09
origin ber this sub 改變 turn src gin 怎麽
watch和computed是vue框架中很重要的特性。
那麽,他們是怎麽作用於對象數組的?
今天我們就來探究一下。
上代碼。
<template> <div class="hello"> {{ msg }} <div> <button @click="submit">plus</button> </div> <div>{{ testNum }}</div> </div> </template> <script> export default { name: ‘abc‘, data () { return { msg: ‘Welcome to Your Vue.js App‘, originNum:0, originObj:[ ] } }, computed: { testNum(){ console.log("computed") if (this.originObj.length=== 0) { this.$set(this.originObj, 0, {number:0}) return this.originObj[0].number } let obj = this.originObj[0] obj.number = -obj.number this.$set(this.originObj, 0, obj) return this.originObj[0].number } }, watch:{ originObj:{ handler:function (val, oldVal) { console.log("watch") }, deep:true } }, created(){ }, mounted(){ }, methods:{ submit(){ let obj = this.originObj[0] obj.number = 100 this.$set(this.originObj, 0, obj) } } }; </script> <style scoped> </style>
首先是初始化(進入這個頁面時)。
從日誌中可以看到,先調用了computed,再調用了watch。
看代碼。數據綁定是綁定了computed:testNum,所以初始化時就會調用。
if (this.originObj.length === 0) { this.$set(this.originObj, 0, {number:0}) return this.originObj[0].number }
因為初始的對象數組originObj沒有對象,所以加了一個對象。watch監聽到originObj改變了,所以打了日誌。
submit(){ let obj = this.originObj[0] obj.number = 100 this.$set(this.originObj, 0, obj) }
然後,我點擊按鈕,觸發submit()方法。
再看日誌,分別觸發了watch computed watch。
submit()方法修改了this.originObj[0].number,this.originObj的watch加了deep:true,所以可以監聽到,watch打進日誌。
this.originObj改變了,所以觸發了computed:testNum(計算屬性computed有緩存,只在值改變時觸發),computed打進日誌。
computed:testNum觸發的時候同時也修改了this.originObj,所以再次觸發watch,watch打進日誌。
以上。
vue : watch、computed、以及對象數組