Vue 3 OTP Input Component

0.5.40 · active · verified Sun Apr 19

vue3-otp-input is a fully customizable, one-time password (OTP) input component designed for Vue 3 applications, leveraging the Vue Composition API. The current stable version is `0.5.40`, with a consistent release cadence addressing bug fixes and minor enhancements. Key differentiators include robust handling of mobile autofill, improved focus behavior, and specific fixes for iOS input issues, which were addressed in recent `0.5.x` releases. It is a lightweight component that ships with TypeScript types, providing a seamless integration experience for developers building modern Vue applications requiring secure and user-friendly OTP entry forms.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic usage of the OtpInput component in a Vue 3 Single File Component (SFC). It includes `v-model` for two-way data binding, sets the number of inputs and auto-focus, defines input types and styling, and handles `on-change` and `on-complete` events. It also shows how to clear the OTP programmatically.

<template>
  <div class="otp-container">
    <h2>Enter OTP</h2>
    <OtpInput
      ref="otpInputRef"
      v-model:value="otpValue"
      :numInputs="6"
      :shouldAutoFocus="true"
      :input-type="['number', 'text']"
      :input-classes="['otp-input']"
      separator="-"
      @on-change="handleOnChange"
      @on-complete="handleOnComplete"
    />
    <p v-if="otpValue">Current OTP: {{ otpValue }}</p>
    <button @click="clearOtp">Clear OTP</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import OtpInput from 'vue3-otp-input';

const otpValue = ref<string>('');
const otpInputRef = ref<InstanceType<typeof OtpInput> | null>(null);

const handleOnChange = (value: string) => {
  console.log('OTP Changed:', value);
};

const handleOnComplete = (value: string) => {
  console.log('OTP Complete:', value);
  alert(`OTP Completed: ${value}`);
  // In a real application, you might submit the OTP here
};

const clearOtp = () => {
  otpValue.value = '';
  otpInputRef.value?.clearInput(); // Using the clearInput method exposed by the component
};
</script>

<style scoped>
.otp-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  max-width: 400px;
  margin: 50px auto;
}
.otp-input {
  width: 40px;
  height: 40px;
  padding: 5px;
  margin: 0 5px;
  text-align: center;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1.2em;
}
.otp-input:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
}
</style>

view raw JSON →