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
- Add the
ref
attribute with avalue
to the element like this.
<template>
<input ref="nameInput" /></template>
- Now, in the component
<script>
tag we can access the above element usingthis.$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 thecreated()
lifecycle hook, computed properties.