Understanding Vue refs
In Vue, refs are references to DOM elements or other component instances that have been mounted to the DOM.
One of the major use cases for refs is direct DOM manipulation and integration with DOM-based libraries (that usually take a DOM node they should mount to), such as an animation library.
We define refs by using the syntax ref="name"
on a native element or child component in the template. In the following example, we will add a reference to the input element under the name theInput
:
<template> <div id="app"> <input ref="theInput" /> </div> </template>
Refs can be accessed from the Vue component instance through this.$refs[refName]
. So, in the preceding example, where we had a ref defined as ref="theInput"
, it can be accessed through this.$refs.theInput
.
Now let’s programmatically focus on the input
field when clicking...