Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get changes in Vue updated hook?

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.

like image 346
serverpunk Avatar asked May 03 '17 15:05

serverpunk


People also ask

How do I watch data changes on Vue instance?

vue file we can watch for changes in data or props by using watch . For example, the below code will watch for a change in the data element pageData , and run a function according to the value it is changed to.

How do I Rerender components in Vue?

The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.

What is life cycle hook in Vue?

Lifecycle hooks are pre-defined methods that get executed in a certain order, starting from the initialization of the Vue instance to its destruction. Below is a diagram that indicates the Vue JS lifecycle hooks sequence. There are eight lifecycle hooks in Vue JS: beforeCreate. created.

What is the life cycle of Vue component?

Each Vue component instance goes through a series of initialization steps when it's created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes.


1 Answers

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.

like image 53
thanksd Avatar answered Oct 07 '22 01:10

thanksd