what's the real purpose of 'ref' attribute?
I'm really confused with the "ref" attribute of the input element. I've never heard it based on my knowledge and can't find some meaningful materials about it.The code is in vue.js offical documents.
<currency-input v-model="price"></currency-input>
This is code about the component:
Vue.component('currency-input', {
template: `
<span>
$
<input
ref="input"
v-bind:value="value"
v-on:input="updateValue($event.target.value)">
</span>
`,
props: ['value'],
what's the meaning of the value of ref attribute that equals to input?
The main purpose of the ref attribute is to make the DOM element selectable by being the key in the parent $refs
attribute.
For example your input element there, with ref="input"
, would expose its DOM node in its parent (here inside currency-input this
), as this.$refs["input"]
(or this.$refs.input
).
See: https://vuejs.org/v2/api/#ref
It has several use cases, even if it would be often better when possible to not manipulate the DOM directly. For example, a legitimate use case here is to put focus on this input: for that you can use this.$refs["input"].focus()
in a method of the component...
-
$refs
is used to select/target HTML elements -
$refs
is like thedocument.querySelector('.el')
in vanilla JS or$('.el')
in jQuery -
$refs
can be accessed inside or outside your VueJS instance. -
$refs
are NOT REACTIVE unlike data properties.
Thus, it is recommended to use $refs
when you want to listen/manipulate/change the value of an element that doesn't connected/controlled to any Vue instance properties to avoid conflicts.
There's one use case I find ref
attribute particularly useful is in Vue component testing. Adding ref
attribute to your html element makes it easily retrieved in testing (e.g. const fooRef = wrapper.find({ ref: 'foo' })
). This is particularly handy when you do not want to add id or class attributes as they are usually also used for styling purposes, for example, adding classes just for identifying element could result in unexpected styles if these names are already (or later on) being used in global style sheets.