How to get changes in Vue updated hook?

javascript, vue.js

Solution

The `updated` lifecycle hook doesn't provide any information on what caused the Vue component instance to be updated. The best way to react to data changes is by using watchers.

However, if you're trying to investigate what caused an update for debugging purposes, you can store a reference to the state of the Vue instance's data and compare it to the state when updated.

Here's an example script using lodash to log the name of the property that changed, triggering the update:

updated() {
  if (!this._priorState) {
    this._priorState = this.$options.data();
  }

  let self = this;
  let changedProp = _.findKey(this._data, (val, key) => {
    return !_.isEqual(val, self._priorState[key]);
  });

  this._priorState = {...this._data};
  console.log(changedProp);
},

This works because properties prepended with the underscore character are reserved for internal use and are not available for binding. This could be saved in a mixin to use whenever you needed to debug a Vue component this way.

Here's a working fiddle for that example.

Problem

If I have a Vue component like: ``` <script> export default { updated() { // do something here... } }; </script> ``` is there anyway to get the changes that resulted in the update? Like how `watch` hooks accept arguments for previous and next data? ``` watch: { someProp(next, prev) { // you can compare states here } } ``` React seems to do this in `componentDidUpdate` hooks, so I'm assuming Vue has something similar but I could be wrong.

Original source