How to use ref for a form?
Using ref for a form in Vue means getting direct access to the form's DOM element or its fields, in order to:
- read values directly,
- validate the form,
- reset fields,
- call the native form's methods (
reset(),submit()), - work with third-party UI libraries.
This is done differently in the Options API and the Composition API, but the logic is the same.
1. Using ref with a form in the Composition API
Template:
html
<form ref="formRef" @submit.prevent="handleSubmit">
<input v-model="name" />
<input v-model="email" />
</form>Script setup:
vue
<script setup>
import { ref, onMounted } from 'vue'
const formRef = ref(null)
const name = ref('')
const email = ref('')
onMounted(() => {
console.log(formRef.value) // the <form> element
})
function handleSubmit() {
console.log("Submitting the form")
console.log(formRef.value) // you can work with the DOM directly
}
</script>What can you do with a ref to the form?
1. Resetting the form
js
formRef.value.reset()2. Programmatic submission
js
formRef.value.submit() // triggers a native submit3. Getting field values (like in plain JS)
js
const data = Object.fromEntries(new FormData(formRef.value))
console.log(data)4. Focusing a form field
js
formRef.value.querySelector('input').focus()5. Validation
js
if (!formRef.value.checkValidity()) {
console.log("The form is invalid")
}2. Using ref in the Options API
html
<form ref="myForm" @submit.prevent="submitForm">
<input v-model="name">
</form>js
export default {
data() {
return { name: '' }
},
methods: {
submitForm() {
console.log(this.$refs.myForm) // the DOM form
}
},
mounted() {
console.log(this.$refs.myForm) // available here
}
}Important rules
ref is only available after mounted
Before mounted() -> null.
ref is direct access to the DOM
Vue does not get in the way of native actions on the form.
You can use ref on the form itself or on its field
html
<input ref="emailInput">js
emailInput.value.focus()Example of full form handling with ref
vue
<template>
<form ref="formRef" @submit.prevent="onSubmit">
<input name="email" v-model="email">
<input name="password" v-model="password">
<button type="submit">Login</button>
</form>
</template>
<script setup>
import { ref } from 'vue'
const email = ref('')
const password = ref('')
const formRef = ref(null)
function onSubmit() {
const formData = new FormData(formRef.value)
console.log(Object.fromEntries(formData))
}
</script>Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.