Purpose of ‘ref’ attribute in Vue.js
Ref attribute’s main purpose is to make the DOM element
selectable by being the key in the parent $refs attribute. $refs is like the
document.querySelector(‘.el’) in vanilla JS $(‘.el’) in jQuery. It can be
accessed inside or outside of your Vue.js instance.
<currency-input v-model="price"></currency-input>
Example code:
Vue.component('currency-input', {template: `
<span>
$
<input
ref="input"
v-bind:value="value"
v-on:input="updateValue($event.target.value)">
</span>
`,
props: ['value'],
In the code, the input element with ref=”input” would expose
its DOM node in its parent as this.$refs[“input”] or this.$refs.input. The ref attribute is
used to register a reference to an element or a child component. When using ref
on a plain DOM element, the reference will be that element. When used on the child
component the reference will be the component instance.
Comments
0 comments
Please Sign in or Create an account to Post Comments