Created
October 16, 2024 16:54
-
-
Save byronferguson/7308de5bb3dd8d737291d17704d322a2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<label :for="name" class="label">{{ label }}</label> | |
<input | |
:id="name" | |
ref="el" | |
v-model="input" | |
type="text" | |
class="rounded-input" | |
:required="required" | |
:name="name" | |
/> | |
<client-only> | |
<FieldErrorDisplay v-if="displayError" :errors="errors" /> | |
</client-only> | |
</div> | |
</template> | |
<script lang="ts"> | |
import { defineComponent, SetupContext, computed, watch } from '@nuxtjs/composition-api'; | |
import { useInputValidator } from '~/composables/use-inputValidator'; | |
import FieldErrorDisplay from '~/components/global/FieldErrorDisplay.vue'; | |
import { required } from '~/lib/validators'; | |
interface Props { | |
name: string; | |
value: string; | |
validators: any[]; | |
required: boolean; | |
} | |
export default defineComponent({ | |
name: 'BbTextInput', | |
components: { | |
FieldErrorDisplay, | |
}, | |
props: { | |
name: { | |
type: String, | |
required: true, | |
}, | |
label: { | |
type: String, | |
required: true, | |
}, | |
value: { | |
type: String, | |
required: true, | |
}, | |
validators: { | |
type: Array, | |
required: false, | |
default: () => [], | |
}, | |
required: { | |
type: Boolean, | |
required: false, | |
default: false, | |
}, | |
}, | |
setup(props: Props, { emit }: SetupContext) { | |
const validators = props.required ? [required(), ...props.validators] : [...props.validators]; | |
const { el, input, errors, isValid } = useInputValidator( | |
props.value, | |
validators, | |
(value: string) => { | |
emit('validate', { name: props.name, isValid: isValid.value }); | |
emit('input', value); | |
}, | |
); | |
watch( | |
() => props.value, | |
newValue => { | |
input.value = newValue; | |
}, | |
); | |
const displayError = computed(() => !!input.value || (!input.value && props.required)); | |
return { | |
el, | |
input, | |
errors, | |
displayError, | |
}; | |
}, | |
}); | |
</script> | |
<style lang="postcss" scoped> | |
/* .input__required { | |
&:required:focus { | |
@apply border-red-600; | |
} | |
} */ | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment