How to validate a form with ref in Vue Composition API

Viewed 9320

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?

2 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

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
    }
  }
}
Related