Skip to content

Instantly share code, notes, and snippets.

@marr
Created November 21, 2022 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marr/7052edca47fb7b0a888fcd8952e13397 to your computer and use it in GitHub Desktop.
Save marr/7052edca47fb7b0a888fcd8952e13397 to your computer and use it in GitHub Desktop.
<template>
<div>
<label class="block text-sm font-medium text-gray-700" :for="name">{{
label
}}</label>
<div class="mt-1 rounded-md shadow-sm">
<input
:class="classes"
:id="id || name"
:name="name"
:type="type"
v-model="value"
v-on="handlers"
/>
</div>
<ErrorMessage class="text-pink-600" :name="name" />
</div>
</template>
<script setup>
import { computed, defineProps, toRef } from 'vue';
import { ErrorMessage, useField } from 'vee-validate';
const props = defineProps({
id: String,
label: String,
name: {
required: true,
type: String,
},
type: {
default: 'text',
type: String
}
});
// Set options to prevent always validating. We use "eager" validation described below
const { errorMessage, meta, value, handleChange, handleBlur } = useField(toRef(props, 'name'), null, {
validateOnValueUpdate: false
});
// Tailwind/DOM :invalid pseudo-class not available, so manually append the classes.
const classes = computed(() => [
'mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md',
// :disabled inputs
'disabled:bg-slate-50 disabled:text-slate-500 disabled:border-slate-200 disabled:shadow-none',
// :invalid inputs
{ 'border-pink-500 text-pink-600 focus:border-pink-500 focus:ring-pink-500 shadow-pink-200/50': meta.validated && !meta.valid }
]);
// Eager validation: check on: blur, change, input (when there is an error message already)
const handlers = computed(() => ({
blur: handleBlur,
change: handleChange,
input: (e) => handleChange(e, !!errorMessage.value),
}));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment