I am currently exploring the use of VeeValidate within a custom input component.
In my attempts, I have experimented with using $emit
on both @input
and @blur
events. However, I have encountered an issue where validation takes place in the next tick, causing me to miss capturing the validation event.
onEvent (event) {
console.log('error length', this.errors.items.length)
if (this.errors.items.length) {
this.hasError = true
this.$emit('has-error',this.errors.items)
} else {
this.hasError = false
this.$emit('on-input', event)
}
}
I also tried injecting the validator from the parent component to directly access the errors computed property. However, due to multiple levels of nesting between the parent page and the custom input component, this approach led to complications. The components are designed for reusability, so injecting the validator through all layers is not ideal.
export default {
//in custom input component
inject: ['$validator'],
}
The most promising solution I came up with involves watching the changes in the errors computed property and emitting an event when a change occurs with the errors specific to that instance of the component.
watch: {
errors: function (errorsNew) {
console.log('errors watch',errorsNew)
}
},
However, I faced difficulties in watching the errors computed property introduced by vee-validate.
Here is a simplified version of the code:
Parent Component:
<template>
<div id="app">
<CustomInput
:label="'Label1'"
:value="'value from store'"
:validations="'required|max:10|min:5'"
:name="'label1'"
/>
<button>Save</button>
</div>
</template>
<script>
import CustomInput from "./components/CustomInput";
export default {
name: "App",
components: { CustomInput }
};
</script>
Custom Input Component:
<template>
<div>
<label >{{ label }}</label>
<input :value="value" :name="name" v-validate="validations">
<span v-if="this.errors.items.length">{{this.errors.items[0].msg}}</span>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
label: {
type: String,
required: true
},
value: {
type: String,
default: ""
},
validations: {
type: String,
default: ""
},
name: {
type: String,
required: true
}
},
watch: {
errors: function(errorsNew) {
console.log("errors watch", errorsNew);
this.$emit('has-error')
}
}
};
</script>
If anyone can assist me in accessing the validation errors from the custom input component, I would greatly appreciate it.
Update:
I have created a simple fiddle for easier testing: https://codesandbox.io/s/mqj9y72xx