Here is an example of how you can make a reusable OTP input field with Vue 3 and Tailwind CSS:
- Create a new Vue component called
OtpInput.vue
- In the template section, use Tailwind CSS classes to style the input field and any other elements you want to include (e.g. a container div, a label, etc.).
- In the script section, create a
data
object with a property for the OTP value and any other props that you want to pass to the component. - Create a method that updates the OTP value when the input field is changed.
- In the script section, use the
props
option to specify any props that should be passed to the component. - In the parent component, import the
OtpInput
component and use it in the template. Pass any props that you specified in theOtpInput
component. - Use the emitted value of otp input field.
<template>
<div class="relative rounded-md shadow-sm">
<input
:value="otp"
@input="updateOtp"
class="form-input py-3 px-4 rounded-md leading-5 text-gray-700 transition duration-150 ease-in-out"
/>
</div>
</template>
<script>
export default {
name: "OtpInput",
props: {
value: {
type: String,
default: "",
},
},
data() {
return {
otp: this.value,
};
},
methods: {
updateOtp(e) {
this.otp = e.target.value;
this.$emit("input", this.otp);
},
},
};
</script>
<style>
/* Add any custom styles for the component here */
</style>
In parent component,
<template>
<div>
<OtpInput v-model="otp" />
</div>
</template>
<script>
import OtpInput from "./OtpInput";
export default {
name: "Parent",
components: {
OtpInput,
},
data() {
return {
otp: "",
};
},
};
</script>
Now you can use the otp
value in the parent component and also validate it as per requirement.
(Visited 7 times, 1 visits today)
Was this article helpful?
YesNo
Last modified: January 16, 2023