With the Options API
, I validated my form like this:
template:
<v-form ref="form" v-model="valid" lazy-validation @submit.prevent>
...
script:
methods: {
validate() {
this.$refs.form.validate();
...
}
}
Now, with new Composition API
, how I can call validate()
on form?
Ref s are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.
Vue can store references to DOM elements in a property called $ref . The first thing we have to do, is add a ref attribute to the element we want to reference in our Javascript. The value of the ref attribute will be the name of it within the $ref property.
Unlike ref , reactive can only be initialized with an object. Each property of the object can be a different reactive variable, however. One advantage of reactive is that it doesn't use a value property so it may be a little easier to read. It also means it looks the same in JavaScript as in the template.
First, setup your template ref by declaring a ref
with the same name as used in the template (1️⃣). Then, return a validate
method from your setup()
(2️⃣):
<template>
<v-form ref="myForm">...</v-form>
</template>
<script>
import { ref } from '@vue/composition-api'
export default {
setup() {
const myForm = ref(null) // 1️⃣
return {
myForm, // 1️⃣
validate() { // 2️⃣
myForm.value.validate()
},
}
}
}
</script>
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