'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?



Solution 1:[1]

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

Solution 2:[2]

Vue 2 + composition api :

You could get access to that ref via the context which is the second parameter of the setup function:

<v-form ref="form" v-model="valid" lazy-validation @submit.prevent="validate">

script :

export default {
  setup(props,context) {
    functions validate() { 
       context.refs.form.validate()
      }

    return {
       validate
    }
  }
}

or destruct that context inside the parameter :

export default {
  setup(props,{refs}) {
    functions validate() { 
      refs.form.validate()
      }

    return {
       validate
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Boussadjra Brahim
Solution 2