Here is an example of how you can make a reusable OTP input field with Vue 3 and Tailwind CSS:

  1. Create a new Vue component called OtpInput.vue
  2. 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.).
  3. 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.
  4. Create a method that updates the OTP value when the input field is changed.
  5. In the script section, use the props option to specify any props that should be passed to the component.
  6. In the parent component, import the OtpInput component and use it in the template. Pass any props that you specified in the OtpInput component.
  7. 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 194 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window