PasswordInput.vue 11.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
<script setup lang="ts">
import { nextTick, ref, watch } from 'vue';

interface Props {
  modelValue: boolean;
  title?: string;
  length?: number;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'complete', password: string): void;
  (e: 'cancel'): void;
}

const props = withDefaults(defineProps<Props>(), {
  title: '请输入支付密码',
  length: 6,
});

const emit = defineEmits<Emits>();

// 密码输入框数组
const passwordValues = ref<string[]>(
  Array.from({ length: props.length }).fill(''),
);
const inputRefs = ref<HTMLInputElement[]>([]);
const currentIndex = ref(0);

// 设置输入框引用
const setInputRef = (el: any, index: number) => {
  if (el) {
    inputRefs.value[index] = el;
  }
};

// 处理输入
const handleInput = (index: number, event: Event) => {
  const target = event.target as HTMLInputElement;
  let value = target.value;

  // 只允许输入数字
  value = value.replaceAll(/\D/g, '');

  // 只保留第一个字符
  if (value.length > 1) {
    value = value.charAt(0);
  }

  passwordValues.value[index] = value;
  target.value = value;

  // 如果输入了数字,自动聚焦到下一个输入框
  if (value && index < props.length - 1) {
    currentIndex.value = index + 1;
    nextTick(() => {
      inputRefs.value[index + 1]?.focus();
    });
  }

  // 检查是否已完成输入
  checkComplete();
};

// 处理键盘事件
const handleKeydown = (index: number, event: KeyboardEvent) => {
  // 处理退格键
  if (event.key === 'Backspace') {
    event.preventDefault();

    if (passwordValues.value[index]) {
      // 如果当前框有值,清空当前框
      passwordValues.value[index] = '';
      (event.target as HTMLInputElement).value = '';
    } else if (index > 0) {
      // 如果当前框没值,回退到上一个框并清空
      currentIndex.value = index - 1;
      passwordValues.value[index - 1] = '';
      nextTick(() => {
        const prevInput = inputRefs.value[index - 1];
        if (prevInput) {
          prevInput.value = '';
          prevInput.focus();
        }
      });
    }
  }

  // 禁用左右箭头键
  if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
    event.preventDefault();
  }
};

// 处理粘贴事件
const handlePaste = (index: number, event: ClipboardEvent) => {
  event.preventDefault();
  const pasteData = event.clipboardData?.getData('text') || '';
  const numbers = pasteData.replaceAll(/\D/g, '');

  if (numbers) {
    // 从当前位置开始填充
    for (let i = 0; i < numbers.length && index + i < props.length; i++) {
      passwordValues.value[index + i] = numbers[i];
      if (inputRefs.value[index + i]) {
        inputRefs.value[index + i].value = numbers[i];
      }
    }

    // 聚焦到最后一个填充的位置或下一个空位
    const nextEmptyIndex = passwordValues.value.findIndex(
      (v, i) => i >= index && !v,
    );
    if (nextEmptyIndex === -1) {
      currentIndex.value = props.length - 1;
      nextTick(() => {
        inputRefs.value[props.length - 1]?.focus();
      });
    } else {
      currentIndex.value = nextEmptyIndex;
      nextTick(() => {
        inputRefs.value[nextEmptyIndex]?.focus();
      });
    }

    checkComplete();
  }
};

// 处理聚焦事件 - 定位到正确输入位置并唤起软键盘
const handleFocus = (index: number) => {
  // 找到第一个空的输入框位置
  const firstEmptyIndex = passwordValues.value.findIndex((v) => !v);
  const targetIndex =
    firstEmptyIndex === -1 ? props.length - 1 : firstEmptyIndex;

  // 如果聚焦的不是当前应该输入的位置,则重新聚焦到正确位置
  if (index !== targetIndex) {
    nextTick(() => {
      inputRefs.value[targetIndex]?.focus();
    });
  }
  currentIndex.value = targetIndex;
};

// 处理点击事件 - 确保软键盘唤起
const handleClick = (index: number) => {
  // 在下一帧确保输入框获得焦点,从而唤起软键盘
  nextTick(() => {
    const firstEmptyIndex = passwordValues.value.findIndex((v) => !v);
    const targetIndex =
      firstEmptyIndex === -1 ? props.length - 1 : firstEmptyIndex;
    inputRefs.value[targetIndex]?.focus();
    currentIndex.value = targetIndex;
  });
};

// 检查是否完成输入
const checkComplete = () => {
  const password = passwordValues.value.join('');
  if (password.length === props.length) {
    // 延迟一点点,让用户看到最后一个数字输入
    setTimeout(() => {
      emit('complete', password);
    }, 100);
  }
};

// 重置密码
const reset = () => {
  passwordValues.value = Array.from({ length: props.length }).fill('');
  inputRefs.value.forEach((input) => {
    if (input) input.value = '';
  });
  currentIndex.value = 0;
  nextTick(() => {
    inputRefs.value[0]?.focus();
  });
};

// 关闭弹窗
const handleClose = () => {
  emit('update:modelValue', false);
  emit('cancel');
};

// 点击遮罩关闭
const handleMaskClick = (event: MouseEvent) => {
  if (event.target === event.currentTarget) {
    handleClose();
  }
};

// 监听弹窗打开,自动清空并聚焦第一个输入框
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      nextTick(() => {
        reset();
      });
    }
  },
);

// 暴露方法给父组件
defineExpose({
  reset,
});
</script>

<template>
  <Teleport to="body">
    <Transition name="modal">
      <div
        v-if="modelValue"
        class="password-modal-overlay"
        @click="handleMaskClick"
      >
        <Transition name="slide-up">
          <div v-if="modelValue" class="password-modal-content">
            <!-- 头部 -->
            <div class="modal-header">
              <h3 class="modal-title">{{ title }}</h3>
              <button class="close-btn" @click="handleClose">
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <line x1="18" y1="6" x2="6" y2="18" />
                  <line x1="6" y1="6" x2="18" y2="18" />
                </svg>
              </button>
            </div>

            <!-- 主体内容 -->
            <div class="modal-body">
              <div class="password-input-group">
                <input
                  v-for="(value, index) in passwordValues"
                  :key="index"
                  :ref="(el) => setInputRef(el, index)"
                  type="tel"
                  inputmode="numeric"
                  maxlength="1"
                  class="password-input"
                  :class="{
                    active: currentIndex === index,
                    filled: passwordValues[index],
                  }"
                  @input="handleInput(index, $event)"
                  @keydown="handleKeydown(index, $event)"
                  @paste="handlePaste(index, $event)"
                  @focus="handleFocus(index)"
                  @click="handleClick(index)"
                />
              </div>

              <div class="password-tips">
                <p>为了您的资金安全,请输入支付密码</p>
              </div>
            </div>

            <!-- 底部 -->
            <div class="modal-footer">
              <button class="cancel-btn" @click="handleClose">取消</button>
            </div>
          </div>
        </Transition>
      </div>
    </Transition>
  </Teleport>
</template>

<style scoped lang="scss">
// 脉动动画
@keyframes pulse {
  0%,
  100% {
    box-shadow: 0 0 0 3px rgb(234 66 0 / 10%);
  }

  50% {
    box-shadow: 0 0 0 6px rgb(234 66 0 / 5%);
  }
}

// 移动端优化
@media (max-width: 767px) {
  .password-input-group {
    gap: 6px;
  }

  .password-input {
    max-width: 45px;
    height: 48px;
    font-size: 22px;
  }
}

.modal-enter-active,
.modal-leave-active {
  transition: opacity 0.3s ease;
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}

// 内容区域滑入动画
.slide-up-enter-active {
  transition: transform 0.3s cubic-bezier(0.32, 0.72, 0, 1);
}

.slide-up-leave-active {
  transition: transform 0.25s cubic-bezier(0.4, 0, 1, 1);
}

.slide-up-enter-from {
  transform: translateY(100%);
}

.slide-up-leave-to {
  transform: translateY(100%);
}

// 遮罩层
.password-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: rgb(0 0 0 / 50%);
}

// 弹窗内容
.password-modal-content {
  position: relative;
  width: 100%;
  max-width: 100%;
  background: #fff;
  border-radius: 20px 20px 0 0;
  box-shadow: 0 -4px 20px rgb(0 0 0 / 10%);
}

// 头部
.modal-header {
  position: relative;
  padding: 20px 20px 10px;
  border-bottom: 1px solid #f0f0f0;

  .modal-title {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
    text-align: center;
  }

  .close-btn {
    position: absolute;
    top: 20px;
    right: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    padding: 0;
    color: #909399;
    cursor: pointer;
    outline: none;
    background: transparent;
    border: none;
    transition: all 0.3s ease;

    &:hover {
      color: #606266;
      background: #f5f5f5;
      border-radius: 50%;
    }

    &:active {
      transform: scale(0.95);
    }

    svg {
      display: block;
    }
  }
}

// 主体
.modal-body {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 20px 20px;
}

.password-input-group {
  display: flex;
  gap: 8px;
  justify-content: center;
  width: 100%;
  max-width: 360px;
  margin-bottom: 24px;

  @media (min-width: 768px) {
    gap: 12px;
    max-width: 420px;
  }
}

.password-input {
  flex: 1;
  max-width: 50px;
  height: 50px;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  text-align: center;
  appearance: none;
  cursor: pointer;
  caret-color: transparent;
  user-select: none;
  outline: none;
  background: #f9fafb;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;

  @media (min-width: 768px) {
    max-width: 60px;
    height: 60px;
    font-size: 28px;
  }

  &:focus {
    background: #fff;
    border-color: #ea4200;
    box-shadow: 0 0 0 3px rgb(234 66 0 / 10%);
  }

  &.active {
    background: #fff;
    border-color: #ea4200;
    animation: pulse 1.5s ease-in-out infinite;
  }

  &.filled {
    // 显示为星号
    -webkit-text-security: disc;
    text-security: disc;
    font-family: text-security-disc;
    background: #fff;
    border-color: #ea4200;
  }

  // iOS 样式重置
  &::-webkit-inner-spin-button,
  &::-webkit-outer-spin-button {
    margin: 0;
    appearance: none;
  }

  // 禁用选中效果
  &::selection {
    background: transparent;
  }
}

.password-tips {
  text-align: center;

  p {
    margin: 0;
    font-size: 13px;
    line-height: 1.5;
    color: #6b7280;
  }
}

// 底部
.modal-footer {
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 0 20px 20px;
  padding-bottom: calc(20px + env(safe-area-inset-bottom));

  .cancel-btn {
    width: 100%;
    max-width: 360px;
    height: 44px;
    font-size: 16px;
    font-weight: 500;
    color: #6b7280;
    cursor: pointer;
    outline: none;
    background: #f3f4f6;
    border: none;
    border-radius: 12px;
    transition: all 0.3s ease;

    &:hover {
      color: #374151;
      background: #e5e7eb;
    }

    &:active {
      transform: scale(0.98);
    }
  }
}
</style>