This article as originally published at https://www.telerik.com/blogs/how-to-target-the-dom-in-vue
A very common practice in web development is to be target an element in your DOM (Document Object Model) (aka all your HTML elements and the logical structure they represent) and to manipulate it in some way.
In this article we are going to check out the power of ref
and some of its edge cases. Get your toast ready, and let's peel this 🥑.
Knights of the Old Vuepublic
For those of us that come from the old ways, aka jQuery
, we were very used to targeting a DOM element in our page to modify it or use it in any certain way. In fact this was almost unavoidable in cases where you wanted to use any type of plugin that would make use of an element in your page.
In jQuery
, you would select an element by targeting it with the $()
function, and that would open up a wide variety of methods for manipulating this object. Take the example of a div
, where you would like to set or toggle the visibility by switching around the display
css property.
Let's consider the following markup for our example.
<body>
<div id="datOneDiv" class="myCoolClass" style="display: none;">I is hidden</div>
<div>I is shown</div>
<div>I is 🐶</div>
</body>
In jQuery
, this would look like the following.
$('#datOneDiv').css('display', 'block');
A couple of interesting things to mention here. First of all, notice that we're targeting a very specific div
in our document, the one with the id
of datOneDiv
as seen by the selector #datOneDiv
(the # here work just the same as a CSS selector, it denotes an id).
The second thing to note is that as fantastically easy as this was, it prevents a lot of people from actually learning how to JavaScript, which as time go by became a problem.
Do you even JS, breh? 😎💪
In actual vanilla JavaScript, the same result can be achieved by using querySelector
and some property manipulation.
document.querySelector('#datOneDiv').style.display = 'block';
The key thing to notice about this example is that once again, we are making use of an id
to target a very specific div
inside of our document. Granted, we could have also targeted the div
with its class by doing .myCoolClass
, but that as you will learn will present the same problem.
The Vue awakens
We are going to do some Sith killing today, don't worry no actual horned cool looking dudes were harmed in the making of this article.
Consider the following Vue component Sith.vue
.
<template>
<div>
<p class="sithLord">I is Sith</p>
<button @click="keelItWithFire">Kill the Sith DED!</button>
</div>
</template>
<script>
export default {
methods: {
keelItWithFire() {
document.querySelector(".sithLord").style.display = "none";
}
}
};
</script>
I KNOW, I KNOW. Amaga, I should be using dynamic classes, your example is so bad, the avocado is mad and you are no longer my bff. It's alright, I didn't like you anyway. However, for purposes of example let's pretend that we didn't know about all that Vue goodness and that we actually were trying to target the DOM this way to make some changes to it. (Jokes aside, if there is a way you can apply classes or styles dynamically, you should ALWAYS opt for doing it with dynamic properties! We are just doing this as an easy to follow example.)
If we instantiate this component in our App.vue
or our main app entry point, and we click the button you will notice that it actually works. So why exactly have we been told time after time that it is SO BAD to target the DOM directly in Vue like we are doing here?
Try modifying your main template (or wherever you're testing these components) to actually hold two or more Sith lords, like so.
<template>
<div id="app">
<Sith/>
<hr>
<Sith/>
<hr>
</div>
</template>
Now go ahead and click on the second one to kill it ded. HUH. The force is weak with this one. Do you know what happened?
When the component method keelItWithFire
triggers on the second component, the querySelector
method is going through the DOM and trying to find the first instance of an element with the class sithLord
, and sure enough it finds it!
The big issue with targeting the DOM directly in Vue is first of all that components are meant to be reusable and dynamic, so we can not guarantee that the class here is going to be unique
.
Well, we can use an id
you see! And you are partially correct, assigning an id
attribute to a template in Vue will sort of guarantee its uniqueness, proven that you don't instantiate more than a single one of those components in your whole application (else you're basically going to run into the same problem as above).
The second caveat is that you will also have to guarantee that no other thing in your app, no other developer, and no other library is going to create an element that can potentially hold the same id
.
The way of the Vuedi
Vue or do not, there is no try.
In Vue we have plenty of tools to modify the template dynamically through computed properties, local state, dynamic bindings and more. But there will come a time where you will be faced with the need to actually target the DOM. A couple of common reasons are to implement an external party plugin that is not vue specific, or to target a field in a form and focus it, for example.
When such a case arises, we have a pretty cool attribute we can slap to elements called ref
, you can check out the official documentation for it here https://vuejs.org/v2/api/#ref.
We are going to make a new component, this time a Jedi.vue
and this time we are going to do things as we are meant to in Vue.
<template>
<div>
<p ref="jedi">I is Jedi</p>
<button @click="keelItWithFire">Kill the Jedi DED!</button>
</div>
</template>
<script>
export default {
methods: {
keelItWithFire() {
this.$refs.jedi.style.display = "none";
}
}
};
</script>
What, you thought because they were Jedi we weren't going to 🔥? Ain't no one mess with tiny hippo, ain't NO ONE 😠.
Now, the important thing here is to understand what is going on when we add a ref
attribute to one of the elements on our <template>
. In simple terms, each component instance will now hold a private reference pointing to their own <p>
tag, which we can target as seen on the keelItWithFire
function via the $refs
property of the instance.
Other than the problems that arise with class and id targeting, it is of utmost importance to know that the biggest issue of all is that modifying DOM directly can lead to those changes being overwritten by Vue when there is a re-render cycle of the DOM either on that component or its parent.
Since when we target the DOM directly Vue doesn't know about it, it won't update the virtual "copy" that it has stored - and when it has to rebuild, all those changes will be completely lost.
If you don't want a certain piece of your DOM to constantly become re-rendered by Vue, you can apply the v-once
attribute to it, that way it will not try to re-render that specific part.
So far this example doesn't seem super exciting but before we jump to a real case scenario, I want to touch up on some caveats.
Caveat 1
If you use ref
on top of a Vue component, such as <Jedi ref="jedi">
, then what you get out of this.$refs.jedi
will be the component instance, not the element
as we are here with the <p>
tag. This means that you have access to all the cool Vue properties and methods, but also that you will have to access to the root element of that component through $el
if you need to make direct DOM changes.
Caveat 2
The $refs
are registered after the render
function of a component is executed. What this means is that you will NOT be able to use $refs
on hooks that happen before render
is called, for example on created()
, you will however have it available on mounted()
.
There is a way to wait for created()
to have the elements available, and it is by leveraging the this.$nextTick
function.
What this.$nextTick
will do is that it will hold out on executing the function you pass to it until the next DOM update by Vue.
Consider the following example.
<template>
<div>
<p ref="myRef">No</p>
</div>
</template>
<script>
export default {
created() {
if (!this.$refs.myRef) {
console.log("This doesn't exist yet!");
}
this.$nextTick(() => {
if (this.$refs.myRef) {
console.log("Now it does!");
}
});
},
mounted() {
this.$refs.myRef.innerHTML = "🥑";
console.log("Now its mounted");
}
};
</script>
We have a <p>
tag with a ref
of myRef
, nothing fancy there. On the created()
hook though theres a couple of things going on.
First, we make a check to see if this.$refs.myRef
is available to us, and as expect it will not be because the DOM has not yet being rendered at this point - so the console.log will be executed.
After, we are setting an anonymous function to be called on $nextTick
, which will be executed after the DOM has had its next update cycle. Whenever this happens, we will log to the console "Now it does!".
On the mounted()
hook, we actually use this ref
to change the inner text of the <p>
tag to something more worthwhile of our savior the magical avocado, and then we console log some more.
Keep in mind that you will actually get the console logs in this order:
- This doesn't exist yet!
- Now its mounted
- Now it does!
mounted()
actually will fire before nextTick
because nextTick
happens at the end of the render cycle.
The dark side
Well, now that you have all the awesome theory, what we can we actually do with this knowledge? Let's take a look at a common example, bringing in a third party library - flatpickr
, into one of our components. You can read more about flatpickr
here, https://flatpickr.js.org/.
Consider the following component.
<template>
<input
ref="datepicker"
/>
</template>
<script>
import flatpickr from 'flatpickr';
import 'flatpickr/dist/themes/airbnb.css';
export default {
mounted () {
const self = this;
flatpickr(this.$refs.datepicker, {
mode: 'single',
dateFormat: 'YYYY-MM-DD HH:mm'
});
}
};
</script>
First, we import the library and some required styles, but then the package requires that we target a specific element in our DOM to attach itself to, we are using ref
here to point the library towards the correct element
with this.$refs.datepicker
.
This technique will work even for jQuery
plugins.
But beware of the dark side. Angerlar, jFear, Reactgression; the dark side of the Force are they. (Disclaimer, this is a joke. I don't actually dislike the other frameworks. Except maybe jQuery, jQuery is evil.)
Wrapping up
Hope you had some fun learning about ref
today, it's a misunderstood and underused tool that will get you out of trouble when used in the right moment!
The sandbox with the code examples used in this article can be found on the following link: https://codesandbox.io/s/target-dom-in-vue-r9imj
As always, thanks for reading and share with me your ref experiences on twitter at: @marinamosti
PS. All hail the magical avocado 🥑
PSS. ❤️🔥🐶☠️
Top comments (0)