by Sai gowtham

How to access the dom nodes in VueJS using refs

How to access the dom nodes in VueJS using refs

In this tutorial, we are going to learn about how to access the dom nodes in VueJS by using refs.

Refs

If we add ref attribute to any HTML element inside the template that can be accessed in vue instance with $refs property.

Let’s see an example.

<template>
  <div>
     <label for="box">Search : </label>
    <input ref="search" v-model="query" id="box" />  </div>
</template>

<script>
export default {
  data: function() {
    return {
      query: ""
    };
  },
  mounted: function() {    this.$refs["search"].focus();
  }
};
</script>

In the above code, we have added ref atrribute to input element so that we accessed it inside the mounted lifecycle hook with this.$refs['search'].

Whenever a user opens our app we are focussing the input placeholder like Google search box.

vue-refs-input-element

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course