I have a component called TextInput. I need to send v-model with @input event in this component, but I also want it to do validation with vee-validate.
But when I use the handleChange function in the usefield, it does the validation. But this time I cannot send the value with the v-model.
When I do it as follows, I can use the v-model when I use the v-model in the component I call, but it does not do the validation process.
<template>
<div
class="TextInput"
:class="{ 'has-error': !!errorMessage, success: meta.valid }"
>
<label :for="name">{{ label }}</label>
<input
:name="name"
:type="type"
:id="name"
:value="modelValue"
:placeholder="placeholder"
@input="handleChange"
@blur="handleBlur"
v-bind="$attrs"
/>
<p class="help-message" v-show="errorMessage || meta.valid">
{{ errorMessage || successMessage }}
</p>
</div>
</template>
<script>
import { useField } from "vee-validate";
export default {
props: {
type: {
type: String,
default: "text",
},
modelValue:String,
value: {
type: String,
default: "",
},
name: {
type: String,
required: true,
},
label: {
type: String,
required: true,
},
successMessage: {
type: String,
default: "",
},
placeholder: {
type: String,
default: "",
},
},
emits: ['update:modelValue'],
setup(props,{emit}) {
const handleChange = (event) =>{
emit('update:modelValue', event.target.value);
}
const {
errorMessage,
handleBlur,
meta,
} = useField(props.name, undefined, {
initialValue: props.value,
});
return {
handleChange,
handleBlur,
errorMessage,
meta,
};
},
};
</script>
When you do it as below, it doesn't send the v-model, but it does the validation correctly.
<template>
<div
class="TextInput"
:class="{ 'has-error': !!errorMessage, success: meta.valid }"
>
<label :for="name">{{ label }}</label>
<input
:name="name"
:id="name"
:type="type"
:value="inputValue"
:placeholder="placeholder"
@input="handleChange"
@blur="handleBlur"
/>
<p class="help-message" v-show="errorMessage || meta.valid">
{{ errorMessage || successMessage }}
</p>
</div>
</template>
<script>
import { useField } from "vee-validate";
export default {
props: {
type: {
type: String,
default: "text",
},
value: {
type: String,
default: "",
},
name: {
type: String,
required: true,
},
label: {
type: String,
required: true,
},
successMessage: {
type: String,
default: "",
},
placeholder: {
type: String,
default: "",
},
},
setup(props) {
const {
value: inputValue,
errorMessage,
handleBlur,
handleChange,
meta,
} = useField(props.name, undefined, {
initialValue: props.value,
});
return {
handleChange,
handleBlur,
errorMessage,
inputValue,
meta,
};
},
};
</script>
How can I send both validation and v-model in the same way?