How to reference hidden elements in Vue.js

In Vue.js we can reference either Vue.js component or a standard DOM element by marking it with ref="ourReferenceName" inside the HTML tag and later access this element easily inside the component with this.$refs.ourReferenceName.

Let’s have a look at a simple component example:

So far so good.

The problem comes when we want to dynamically hide or show this element, but still need to have access to it. When using e.g. v-if in the template, the element might not be rendered and therefore might not exist yet.

Let’s have a look at an example where our element is hidden first and displayed after:

What we have here is an element that is conditionally hidden and a button that will display it and try to reference it afterwards. This code looks like it could work, but it doesn’t. At the time of accessing the reference, the particular HTML code still has not been rendered yet.

So what now?

It turns out that we can tap into component’s lifecycle method called updated. When updated is called, we can be sure that the rendered HTML reflects our latest changes.

Now we can manipulate our element when it shows up on the page! This technique is useful for example when we need to initialize a JavaScript library on a particular HTML element when this element is hidden behind v-if.

Hope this helps and happy coding!


Loading Likes...

Write a Comment