Vue Js Get Element by ref: In Vue.js, the ref
attribute allows you to reference an element or a component in your template. You can then access this element or component using the $refs
property of your Vue instance. This allows you to perform actions on the element or component, such as changing its properties or invoking its methods. To get an element by its ref
, you can use this.$refs.[refName]
, where refName
is the value of the ref
attribute you assigned to the element.
What is the purpose of using the ref
attribute in Vue.js and how can you get an element or component by its ref
using the $refs
property?
This Vue.js code creates a text input and a button. When the button is clicked, the input value is read and an alert is displayed with the input value. The ref
attribute is used to reference the input element, which can then be accessed using the $refs
property of the Vue instance. The v-model
directive is used to bind the input value to the inputValue
data property. When the button is clicked, the handleClick
method is called, which retrieves the input element by its ref
and reads its value using the value
property.
Vue Js Get Element by ref Example
<div id="app">
<input type="text" ref="myInput" v-model="inputValue" />
<button @click="handleClick">Submit</button>
</div>
<script>
new Vue({
el: '#app',
data() {
return {
inputValue: ''
};
},
methods: {
handleClick() {
const myInput = this.$refs.myInput;
const inputValue = myInput.value;
alert(`Input value is: ${inputValue}`);
}
}
});
</script>