Vue.js Refs
Vue.js Refs
If you're working with Vue.js, you might have heard of refs
before. Refs
is a feature in Vue.js that allows you to access and manipulate DOM elements directly. It's a way to get a reference to a specific element and interact with it programmatically.
The basic syntax for using refs
in Vue.js is to add a ref
attribute to an element you want to reference:
<template>
<div>
<input ref="myInput" v-model="message">
</div>
</template>
In this example, we're adding a ref
attribute to an input element and giving it the name "myInput"
.
Once you've created a ref
, you can use it in your Vue instance using the $refs
property:
<template>
<div>
<input ref="myInput" v-model="message">
<button v-on:click="submitForm">Submit</button>
</div>
</template>
<script>
export default {
data() {
return {
message: "",
}
},
methods: {
submitForm() {
const input = this.$refs.myInput;
console.log(input.value);
}
}
}
</script>
In this example, we're using the $refs
property to get a reference to the input element with the ref="myInput"
attribute. We then use this reference in our submitForm
method to get the value of the input field.
There are many use cases for refs
. For example, you might use them to:
- Focus on an input field when a component is mounted
- Trigger a method when a certain element is clicked
- Access the properties of a child component from a parent component
Overall, refs
provide a simple and powerful way to interact with the DOM in Vue.js.