One of the challenges I'm facing is managing multiple instances of a component called InputWithValidation
within a form. I need to check if all instances are valid at once.
For a single instance of InputWithValidation
, I can easily verify its validity like this:
<script setup>
import { ref } from 'vue'
const inputEmail = ref(null);
function submit(){
if(inputEmail.isValid()){
//call API
}
}
</script>
<template>
<form>
<InputWithValidation ref="inputEmail" type="email" validationType="EMAIL"/>
<button @click="submit">Submit</button>
</form>
</template>
However, dealing with multiple instances poses a challenge:
<template>
<form>
<InputWithValidation ref="inputEmail" type="email" validationType="EMAIL"/>
<InputWithValidation ref="inputFirstName" type="text" validationType="TEXT"/>
<InputWithValidation ref="inputEmail" type="text" validationType="TEXT"/>
<!-- ... -->
<button @click="submit">Submit</button>
</form>
</template>
I don't want to individually declare each instance like this:
<script setup>
import { ref } from 'vue'
const inputEmail = ref(null);
const inputFirstName = ref(null);
const inputEmail = ref(null);
//....
</script>
To tackle this issue, I tried using an array in my ref
to capture all instances and validate them together:
<script setup>
import { ref } from 'vue'
const inputs = ref([]);
function submit(){
if(inputs.find(input => !input.isValid()) == null){
//call API
}
}
</script>
<template>
<form>
<InputWithValidation ref="inputs" type="email" validationType="EMAIL"/>
<InputWithValidation ref="inputs" type="text" validationType="TEXT"/>
<InputWithValidation ref="inputs" type="text" validationType="TEXT"/>
<button @click="submit">Submit</button>
</form>
</template>
Unfortunately, this approach did not work as expected.
Does anyone know of a way to retrieve all references (refs
) at once?