17
9

More than 3 years have passed since last update.

Vue.jsのdeep: trueのwatchでoldValueとnewValueが常に同じ問題の解決

Posted at

時間がある時にもう少し加筆します。

結論

computedで非参照のコピーを作って、そのcomputedをwatchする。

<script>
let vm = new Vue({
  data: {
    human: {
      name: null,
      age: null,
      height: null,
      weight: null
    }
  },
  computed: {
    computedHuman () {
      // 何らかの方法で非参照のコピーを作る
      return JSON.parse(JSON.stringify(this.human))

      // ↓その他
      // return Object.assign({}, this.human)
      // return lodash.cloneDeep(this.human)
    }
  },
  watch: {
    computedHuman: {
      deep: true,
      handler(newValue, oldValue) {
        // ちゃんと中身が異なる
        console.log(newValue)
        console.log(oldValue)
      }
    }
  }
})
</script>

問題: Vue.jsのdeep: trueのwatchではoldValueとnewValueが同じらしい

オブジェクト全体を監視する必要があり、
かつhuman.nameのように個別に監視することができない状態だったのでdeep: trueを試して見ました。

すると、oldValueとnewValueが常に同じでどの値が変更されたのかが分からない状態でした。

<script>
let vm = new Vue({
  data: {
    human: {
      name: null,
      age: null,
      height: null,
      weight: null
    }
  },
  watch: {
    human: {
      deep: true,
      handler(newValue, oldValue) {
        // 中身が同じ!?
        console.log(newValue)
        console.log(oldValue)
      }
    }
  }
})
</script>

参考

newValue and oldValue parameters are the same when deep watching an object - Git Hub

17
9
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
17
9