Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a form with ref in Vue Composition API

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?

like image 714
Philipp Chapkovski Avatar asked Aug 06 '20 00:08

Philipp Chapkovski


People also ask

What is REF () in Vue?

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.

How do you access the ref at Vue?

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.

What is the difference between ref and reactive Vue?

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.


1 Answers

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>

Edit Binding methods with Vue Composition API

like image 196
tony19 Avatar answered Oct 11 '22 14:10

tony19