Vue Ref Dom Element

Posted on  by admin

It’s time to take a closer look at a few more special Vue instance properties and methods, with the first one being the $refs property. But before diving into the JavaScript part of things, let’s start by taking a look at the template.

By adding a ref attribute to any element within the template, we can refer to these elements on our Vue instance. More specifically, we can access the DOM elements. So let’s try it out on the button that I have added in advance.

The button already has a click event handler which doesn’t do anything yet. Note that the ref attribute is not a standard HTML attribute, so it is only used by Vue.

In fact, it won’t even be part of the DOM, so if you inspect the rendered HTML, you won’t see a sign of it.

And, since we didn’t prefix it with a colon, it is not a directive either. We can now reference this button by using the name myButton. We can do this by using the $refs property on our Vue instance.

Let’s log this to the console and see what it looks like. So if I open up the console, we can see that this property is a JavaScript object holding references to all of the elements on which we have added a ref attribute.

Notice that the key names within this object match the names that we specify within the ref attribute, and the values are the DOM elements.

In this case, we can see that the key is myButton and that the value is a native button element which has nothing to do with Vue.js. Therefore we can simply access the DOM element by accessing the name of our reference as a property on the $refs object.

Let’s see that in action. As an example, I will change the text of the button when clicking it.

Clicking the button now, will change its text to “Hello World!”.

Of course we could also have accomplished this with vanilla JavaScript by using a query selector to get access to the DOM element, but using the ref attribute is much cleaner and is the Vue way of doing it. It’s also safer because you won’t be relying on classes and IDs, so the chances of you breaking your code as a result of changing the markup or CSS styles, are lower.

One of the main purposes of a JavaScript framework like Vue is for developers to not have to deal with the DOM.

Therefore you should avoid doing what I just showed you unless you really need to.