Use Cases for Vue’s Updated Hook

Vue.jsPosted on

We can use hooks, watchers and computed properties as well with Vue. However, all of them have a different purpose. Now we try to focus on a hook, that enables us to perform some actions after a component’s DOM is updated. Let’s take a look at the updated hook.

When we are calculating JavaScript values or trigger actions from Vue, maybe it will affect the DOM tree a bit delayed than we would expect. The updated hook lets us perform “callbacks” when the component’s DOM was updated. So here are some cases when using the updated hook is relevant.

Get Dimensions of a Child Node

Let’s say we have a list that is absolute positioned. It means we need to update the parent element’s height if the list items are updated (there can be more or less, the point is the height of the list changes). Let’s set the min-height of the parent to the list’s height when the list is updated.

updated() {
    document.querySelector('.parent-element').style.minHeight = `${this.$el.offsetHeight}px`;
}

Get the Specific Child Nodes

We can create child nodes easily based on a data set by using v-for loop. However, it’s possible, that we need to perform some actions on the nodes, not in the loop but after all the child nodes are rendered. The updated hook is perfect to select all the child nodes and perform the action we want.

updated() {
    this.$el.querySelectorAll('.child-element').forEach(el => {
        //
    });
}

Get Class List of a Child Node

We can bind classes to nodes easily with Vue. However, there are cases, when we use static classes and dynamic classes as well, also maybe we can bind classes natively (with classList) from outside of the component or maybe outside of Vue. With the updated hook we can retrieve all the classes easily.

updated() {
    this.$el.querySelector('.child-element').classList;
}

Wrapping Up

It’s seeable that, the updated hook provides a perfect place when we need to use Vue functionality with DOM elements. Also, it helps us to use native JS what means we can avoid writing helpers and wrappers all the time.

You can find the docs here.

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in Vue.js category