by Sai gowtham

Vue.js: Getting the element in a Component

In this tutorial, we are going to learn about how to get the element inside a component in the Vue app.

Getting the Element

  1. Add the ref attribute with a value to the element like this.
<template>
    <input ref="nameInput" /></template>
  1. Now, in the component <script> tag we can access the above element using this.$refs.nameInput property.
<script>
  export default{
    mounted(){
       console.log(this.$refs.nameInput);    }
  }
</script>

You can also manipulate the element behavior like this.

this.$refs.nameInput.focus();

or you can access the input element value.

this.$refs.nameInput.value;

Note: The $refs are available after a component has been rendered and they are not reactive, so that you should avoid accessing refs inside the created() lifecycle hook, computed properties.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 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)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course