Vue Template Refs
To make references to particular DOM elements, utilize Vue Template Refs.
The DOM element that results from an HTML tag with the ref attribute set is appended to the $refs object.
Instead of using getElementById() or querySelector() in ordinary JavaScript, we may use the ref attribute and the $refs object in Vue.
The 'ref' Attribute and The '$refs' Object
The $refs object will contain HTML tags with the ref attribute, which can subsequently be accessed from within the <script> tag.
Example
A <p> element’s text gets modified.
App.vue:
Example
Click the button to put "Hello!" as the text in the green p element.
This is the initial text
Here’s another example of copying a tag’s value into another tag using the $refs object.
Example
The second <p> tag contains a copy of the text from the first <p> tag.
App.vue:
Example
Click the button to copy this text into the paragraph below.
...
Get The Input Value from '$refs'
To access whatever property we like, we can delve further into an HTML element that has been added to the $refs object.
Example
The content of a <p> element is identical to that entered in the input field.
App.vue:
Example
Start writing inside the input element, and the text will be copied into the last paragraph by the use of the '$refs' object.
'ref' with v-for
The ref attribute-added HTML elements made using v-for will be appended as an array to the $refs object.
Example
The third list element, which is kept as an array element inside the $refs object, is revealed by pressing the button.
App.vue:
Example
Click the button to reveal the 3rd list element stored as an array element in the $refs object.
- {{ x }}
{{ thirdEl }}