Software development and beyond

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:

<template>
<div>
<div ref="referencedElement"></div>
</div>
</template>
<script>
export default {
methods: {
accessElement() {
const element = this.$refs.referencedElement
// TODO: do something with the element
}
}
}
</script>

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:

<template>
<div>
<div v-if="this.shown">
<div ref="referencedElement"></div>
</div>
<button @click="accessElement">Show and access element</button>
</div>
</template>
<script>
export default {
data() {
return {
shown: false
}
},
methods: {
accessElement() {
this.shown = true
const element = this.$refs.referencedElement
// --> error, $refs is not populated yet
}
}
}
</script>

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.

<script>
export default {
updated() {
if (this.shown) {
const element = this.$refs.referencedElement
// TODO: do something with the element
}
},
data() {
return {
shown: false
}
},
methods: {
accessElement() {
this.shown = true
}
}
}
</script>

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!

Last updated on 22.9.2018.

javascript vue-js