18
20

More than 5 years have passed since last update.

Vus.jsでdeep watchをするふたつの方法

Last updated at Posted at 2016-02-01

deep watchオプションを使った書き方はドキュメントに掲載されているのですが、$watchdeep watchする方法は載っていないような気がするのでメモ。

デモ

jsfiddle

解説

$watchの引数として{deep: true}と書けば、deep watchしてくれます。

var app = new Vue({
  el: 'body',
  data: {
    items: [
      { text: 'A'},
      { text: 'B'}
    ]
  },
  watch: {
    'items': {
      handler: function (val, oldVal) {
        console.log('watch 1', 'newval: ', val, '   oldVal:', oldVal)
      },
      deep: true
    }
  }
})

app.$watch('items', function(val ,oldVal){
  console.log('watch 2', 'newval: ', val, '   oldVal:', oldVal)
}, {deep: true})

使い道

$watchで書くとスマートじゃないような気もしますが、メインプログラムとは全く違うところでささっと書きたいときに使えます。

動作はしますが、これが正しい書き方かは不明

なので、注意して使うようにします。

18
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
20