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 ref attribute makes it possible to store a reference to a particular React element or component returned by the component render() configuration function. This can be valuable when you need a reference, from within a component, to some element or component contained within the render() function.
Refs provide a way to access DOM nodes or React elements created in the render method. In the typical React dataflow, props are the only way that parent components interact with their children.
ref is a special attribute, similar to the key attribute discussed in the v-for chapter. It allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted.
Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all.
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 the document.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With