Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Marina Mosti
Marina Mosti

Posted on

     

How to target the DOM in Vue

This article as originally published athttps://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 ofref 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, akajQuery, 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.

InjQuery, 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 adiv, where you would like to set or toggle the visibility by switching around thedisplay css property.

Let's consider the following markup for our example.

<body><divid="datOneDiv"class="myCoolClass"style="display: none;">I is hidden</div><div>I is shown</div><div>I is 🐶</div></body>

InjQuery, 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 specificdiv in our document, the one with theid ofdatOneDiv 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 usingquerySelector 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 anid to target a very specificdiv inside of our document. Granted, we could have also targeted thediv 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 componentSith.vue.

<template><div><pclass="sithLord">I is Sith</p><button@click="keelItWithFire">Kill the Sith DED!</button></div></template><script>exportdefault{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 ourApp.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><divid="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 methodkeelItWithFire triggers on the second component, thequerySelector method is going through the DOM and trying to find thefirst instance of an element with the classsithLord, 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 beunique.

Well, we can use anid you see! And you are partially correct, assigning anid attribute to a template in Vue willsort 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 sameid.

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 calledref, you can check out the official documentation for it herehttps://vuejs.org/v2/api/#ref.

We are going to make a new component, this time aJedi.vue and this time we are going to do things as we are meant to in Vue.

<template><div><pref="jedi">I is Jedi</p><button@click="keelItWithFire">Kill the Jedi DED!</button></div></template><script>exportdefault{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 aref attribute to one of the elements on our<template>. In simple terms, each component instance will now hold aprivate reference pointing to their own<p> tag, which we can target as seen on thekeelItWithFirefunction 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 thev-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 useref on top of a Vue component, such as<Jedi ref="jedi">, then what you get out ofthis.$refs.jedi will be the component instance, not theelement 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 therenderfunction of a component is executed. What this means is that you will NOT be able to use$refson hooks that happen beforerender is called, for example oncreated(), you will however have it available onmounted().

There is a way towait forcreated() to have the elements available, and it is by leveraging thethis.$nextTick function.

Whatthis.$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><pref="myRef">No</p></div></template><script>exportdefault{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 aref ofmyRef, nothing fancy there. On thecreated() hook though theres a couple of things going on.

First, we make a check to see ifthis.$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 themounted() hook, we actually use thisref 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:

  1. This doesn't exist yet!
  2. Now its mounted
  3. Now it does!

mounted() actually will fire beforenextTick becausenextTickhappens 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 aboutflatpickrhere,https://flatpickr.js.org/.

Consider the following component.

<template><inputref="datepicker"/></template><script>importflatpickrfrom'flatpickr';import'flatpickr/dist/themes/airbnb.css';exportdefault{mounted(){constself=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 usingref here to point the library towards the correctelement withthis.$refs.datepicker.

This technique will work even forjQuery 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 aboutref 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Marina Mosti is a full-stack web developer with over 14 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue.
  • Joined

More fromMarina Mosti

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp