2015-12-15 10 views
16
ready: function() { 
    this.$watch('things', function(){console.log('a thing changed')}, true); 
} 

thingsの配列を見るオブジェクト[{foo:1}, {foo:2}]

$watchのアレイは、オブジェクト上の値が変更されたときにオブジェクトを追加または削除ではなく、場合に検出されます。どうやってやるの?

答えて

32

あなたはそう、optionsとして代わりにブールのオブジェクトを渡す必要があります。

ready: function() { 
    this.$watch('things', function() { 
    console.log('a thing changed') 
    }, {deep:true}) 
} 

それとも、このようなvueインスタンスにウォッチャーを設定できます場合は

new Vue({ 
    ... 
    watch: { 
    things: { 
     handler: function (val, oldVal) { 
     console.log('a thing changed') 
     }, 
     deep: true 
    } 
    }, 
    ... 
}) 

[demo]

+0

ニース、これは移行の問題でした。 vueの最後のバージョンでは、最後の引数が 'deep'を意味するため、' true'を使用しました。タイ! –

+0

私のために働いた。ありがとう! – Lorenzo

+0

'ready'はvue 2.0で' mounted'に変更されました! – user1506145

1

をアレイ内で変更されたアイテムを取得する必要がある場合は、それを確認してください:

JSFiddle Example

ポストのコード例:

new Vue({ 
    ... 
    watch: { 
    things: { 
     handler: function (val, oldVal) { 
     var vm = this; 
     val.filter(function(p, idx) { 
      return Object.keys(p).some(function(prop) { 
       var diff = p[prop] !== vm.clonethings[idx][prop]; 
       if(diff) { 
        p.changed = true;       
       } 
      }) 
     }); 
     }, 
     deep: true 
    } 
    }, 
    ... 
})