9

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.

3
  • 1
    watch receives next and prev state to check the changes that resulted in the update, so it looks like that's what you need. UNLESS you are thinking in the DOM changes. in that case you can compare dom using beforeUpdate() and updated() cycle hooks. is that what you need? Commented May 3, 2017 at 15:25
  • I was hoping to get some kind of list of changes in the updated() hook. Is that possible? Commented May 3, 2017 at 15:26
  • Don't know vue enough to reply, sorry. it could inject oldvnode and new vnode, try updated(oldVnode, vNode) { console.log(oldVnode); } and see what happens. Commented May 3, 2017 at 15:31

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.