However, right after I started using Vue I wondered how we could manipulate DOM inside a Vue file. This issue will be resolved by using
$refs to access DOM. Many developers might get the same issue so that I decided to write today's blog post.
So, I refer to it from the official Vue documentation.
refis used to register a reference to an element or a child component. The reference will be registered under the parent component’s
$refsobject. If used on a plain DOM element, the reference will be that element; if used on a child component, the reference will be component instance: https://vuejs.org/v2/api/#ref
<!-- vm.$refs.p will be the DOM node --> <p ref="p">hello</p> <!-- vm.$refs.child will be the child component instance --> <child-component ref="child"></child-component>
I have attached the details of both
ref introduced by the official Vue.js Documentation. However, These are not kind enough for most of the developers who have never experienced using Vue.js.
That's why hopefully this blog post will be a valuable source to help to understand the core concepts about
To clarify the difference between
$refs is the object and all the DOM elements are contained within this object.
$refs itself is useless.
ref should always be registered in the HTML code to take effect
For example, to access to the DOM of the element which is set
this.$refs['slider'] can be accessible to DOM.
In order to confirm the DOM of the one you are supposed to access, you can write
console.log(this.$refs.slider) in mounted().
Then, the result of DOM will be displayed in the console of the dev tool as below.
Until now, I have explained about
The reason why
$refs can be prepared for Vue is that with
$refs we can access the DOM of a parent and child component. Moreover, even DOM of the plugin will be accessible by
$refs into the component code, Please take a deep breath and consider that you do really need
$refs to achieve the expected behavior.
According to the basic concept of Vue.js, we should use Vue's features as much as possible rather than directly manipulate DOM. That's how Vue is welcomed for the developers. We were all fatigued direct manipulation of DOM using jQuery.
To be honest, I have had this mistake several times. It looks so amateur mistake but It has happened it anyway. To make
$refs be applied to the component, the
ref must be set to the target element you want to call out.
ref are the pair used for DOM manipulation.
I personally don't prefer to use or update the code which
$refs are included in several parts. However, sometimes It happens for the Vue developers.
In addition, getting familiar with the specific feature of the daily used technology will eventually help to save your time a lot.
So hopefully, this blog post is worth reading and gaining someone's knowledge. Cheers for all the devs, Thanks!