>  기사  >  웹 프론트엔드  >  vue3에서 6자리 결제 비밀번호 입력란을 구현하는 방법

vue3에서 6자리 결제 비밀번호 입력란을 구현하는 방법

王林
王林앞으로
2023-05-18 09:40:331241검색

특정 요구 사항: 고객 정보 양식의 작업 열에서 결제 비밀번호 수정 버튼을 클릭하면 6자리 결제 비밀번호 입력 상자 구성 요소 페이지로 이동합니다. 동시에 입력 상자는 암호문을 표시해야 하며 편집할 수 없고 되돌릴 수 없으며 즉시 표시됩니다. 6자리에 도달하면 결제 비밀번호 확인 시 자동으로 입력됩니다. 6자리에 도달하면 입력한 두 비밀번호의 일치 여부를 자동으로 확인하고 확인 버튼이 표시됩니다. 이 기능은 고객이 장치를 사용하여 비밀번호를 입력하는 은행에서 사용하기 위한 것입니다. 하지만 창구 직원은 비밀번호를 입력할 수 있습니다.

구체적인 질문: 1. 암호 텍스트를 표시하는 방법, 각 상자에 1자리만 입력할 수 있음 2. 입력란을 편집 및 되돌릴 수 없도록 만드는 방법 3. 일관성을 확인하는 방법; 비밀번호를 두 번 입력했습니다. 4. 회사에서 키보드 키를 제한해야 하는 경우 어떻게 해야 합니까?

vue3에서 6자리 결제 비밀번호 입력란을 구현하는 방법

1. 코드 개요

6자리 결제 비밀번호 입력란 컴포넌트를 구현하는 코드는 다음과 같습니다. 복사해서 바로 사용해보세요!

<template>
  <div >
    <!-- 密码输入框 -->
    <div class="input-box" >
      <!-- 输入密码 -->
      <div >{{ "输入密码" }}</div>
      <div class="input-content" @keyup="keyup" @input="inputEvent">
        <input max="9" min="0" maxlength="1" data-index="0" v-model.number="state.input[0]" type="password"
          ref="firstinput" :disabled="state.disabledInput[0]" />
        <input max="9" min="0" maxlength="1" data-index="1" v-model.number="state.input[1]" type="password"
          :disabled="state.disabledInput[1]" />
        <input max="9" min="0" maxlength="1" data-index="2" v-model.number="state.input[2]" type="password"
          :disabled="state.disabledInput[2]" />
        <input max="9" min="0" maxlength="1" data-index="3" v-model.number="state.input[3]" type="password"
          :disabled="state.disabledInput[3]" />
        <input max="9" min="0" maxlength="1" data-index="4" v-model.number="state.input[4]" type="password"
          :disabled="state.disabledInput[4]" />
        <input max="9" min="0" maxlength="1" data-index="5" v-model.number="state.input[5]" type="password"
          :disabled="state.disabledInput[5]" />
      </div>
      <!-- 确认密码 -->
      <div >{{ "确认密码" }}</div>
      <div class="input-content" @keyup="confirmKeyUp" @input="confirmInputEvent">
        <input max="9" min="0" maxlength="1" data-index="0" v-model.number="state.confirmInput[0]" type="password"
          ref="confirmfirstinput" :disabled="state.disabledConfirmInput[0]" />
        <input max="9" min="0" maxlength="1" data-index="1" v-model.number="state.confirmInput[1]" type="password"
          :disabled="state.disabledConfirmInput[1]" />
        <input max="9" min="0" maxlength="1" data-index="2" v-model.number="state.confirmInput[2]" type="password"
          :disabled="state.disabledConfirmInput[2]" />
        <input max="9" min="0" maxlength="1" data-index="3" v-model.number="state.confirmInput[3]" type="password"
          :disabled="state.disabledConfirmInput[3]" />
        <input max="9" min="0" maxlength="1" data-index="4" v-model.number="state.confirmInput[4]" type="password"
          :disabled="state.disabledConfirmInput[4]" />
        <input max="9" min="0" maxlength="1" data-index="5" v-model.number="state.confirmInput[5]" type="password"
          :disabled="state.disabledConfirmInput[5]" />
      </div>
    </div>
    <!-- 按钮 -->
    <div >
      <el-button type="info" :disabled="state.disabledConfirm" @click="reConfirm"
        :class="[state.disabledConfirm ? &#39;noActive&#39; : &#39;active&#39;]">{{ "确定" }}</el-button>
      <el-button type="warning" @click="reset">{{ "重新输入" }}</el-button>
    </div>
    <!-- 提示区 -->
    <div
      >
      <p>{{ state.tipContent }}</p>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { nextTick, reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from &#39;element-plus&#39;
const state = reactive({
  // 输入数组
  input: ["", "", "", "", "", ""],
  // 确认输入数组
  confirmInput: ["", "", "", "", "", ""],
  // 存放粘贴进来的数字
  pasteResult: [],
  confirmPasteResult: [],
  // 一上来禁用确定按钮
  disabledConfirm: true,
  // 输入框是否禁用
  disabledInput: [false, false, false, false, false, false],
  disabledConfirmInput: [false, false, false, false, false, false],
  // 提示内容
  tipContent: "请告知客户输入6位数字密码,输入完毕后,点击回车确认。"
})
// 获取第一个元素的ref
const firstinput = ref()
const confirmfirstinput = ref()
// 页面一加载就使第一个框聚焦
onMounted(() => {
  // 等待dom渲染完成,在执行focus,否则无法获取到焦点
  nextTick(() => {
    firstinput.value.focus();
  });
})
// @input的处理方法
// 解决一个输入框输入多个字符
const inputEvent = (e) => {
  var index = e.target.dataset.index * 1;
  var el = e.target;
  // 限制只能输入数字
  el.value = el.value.replace(/[^\d]/g, "");
  if (el.value.length >= 1) {
    // 密文显示、不可编辑、不可回退、即时显示
    state.disabledInput[index] = true;
    if (el.nextElementSibling) {
      el.nextElementSibling.focus();
    }
  }
  // 到达6位数,自动进入确认支付密码
  if (!el.nextElementSibling) {
    confirmfirstinput.value.focus();
    state.tipContent = "请告知客户再次输入6位数字密码,输入完毕后,点击回车确认。";
  }
}
// @keydown的处理方法,根据业务需要添加
// 此示例没有使用
const keydown = (e) => {
  var index = e.target.dataset.index * 1;
  var el = e.target;
  // 回退键
  if (e.key === &#39;Backspace&#39;) {
    if (state.input[index].length > 0) {
      state.input[index] = &#39;&#39;
    } else {
      if (el.previousElementSibling) {
        el.previousElementSibling.focus()
        state.input[index - 1] = &#39;&#39;
      }
    }
  }
  // 删除键 
  else if (e.key === &#39;Delete&#39;) {
    if (state.input[index].length > 0) {
      state.input[index] = &#39;&#39;
    } else {
      if (el.nextElementSibling) {
        state.input[1] = &#39;&#39;
      }
    }
    if (el.nextElementSibling) {
      el.nextElementSibling.focus()
    }
  }
  // 左键
  else if (e.key === &#39;ArrowLeft&#39;) {
    if (el.previousElementSibling) {
      el.previousElementSibling.focus()
    }
  }
  // 右键 
  else if (e.key === &#39;ArrowRight&#39;) {
    if (el.nextElementSibling) {
      el.nextElementSibling.focus()
    }
  }
  // 上键 
  else if (e.key === &#39;ArrowUp&#39;) {
    if (Number(state.input[index]) * 1 < 9) {
      state.input[index] = (Number(state.input[index]) * 1 + 1).toString()
    }
  }
  // 下键  
  else if (e.key === &#39;ArrowDown&#39;) {
    if (Number(state.input[index]) * 1 > 0) {
      state.input[index] = (Number(state.input[index]) * 1 - 1).toString()
    }
  }
}
// @keyup的处理方法
const keyup = (e) => {
  var index = e.target.dataset.index * 1;
  // 如果为最后一个框,则输入框全部失焦
  if (index === 5) {
    if (state.input.join("").length === 6) {
      document.activeElement.blur();
    }
  }
}
// @input的处理方法
// 解决一个输入框输入多个字符
const confirmInputEvent = (e) => {
  var index = e.target.dataset.index * 1;
  var el = e.target;
  if (el.value.length >= 1) {
    // 密文显示、不可编辑、不可回退、即时显示
    state.disabledConfirmInput[index] = true;
    if (el.nextElementSibling) {
      el.nextElementSibling.focus();
    }
  }
  // 到达6位数,自动检验两次输入密码的一致性
  if (!el.nextElementSibling) {
    // 一一比较元素值,有一个不相等就不等
    for (let i = 0; i < state.input.length; i++) {
      if (state.input[i] !== state.confirmInput[i]) {
        state.tipContent = "请告知客户两次密码输入不一致,柜员点击重新输入,清空密码后请告知客户重新输入。";
        return;
      }
    }
    state.tipContent = "密码合规,点击确定按钮进行修改。";
    // 确定按钮变为可用
    state.disabledConfirm = false;
  }
}
// @keydown的处理方法,根据业务需要添加
// 此示例没有使用
const confirmKeydown = (e) => {
  var index = e.target.dataset.index * 1;
  var el = e.target;
  // 回退键
  if (e.key === &#39;Backspace&#39;) {
    if (state.confirmInput[index].length > 0) {
      state.confirmInput[index] = &#39;&#39;
    } else {
      if (el.previousElementSibling) {
        el.previousElementSibling.focus()
        state.confirmInput[index - 1] = &#39;&#39;
      }
    }
  }
  // 删除键 
  else if (e.key === &#39;Delete&#39;) {
    if (state.confirmInput[index].length > 0) {
      state.confirmInput[index] = &#39;&#39;
    } else {
      if (el.nextElementSibling) {
        state.confirmInput[1] = &#39;&#39;
      }
    }
    if (el.nextElementSibling) {
      el.nextElementSibling.focus()
    }
  }
  // 左键
  else if (e.key === &#39;ArrowLeft&#39;) {
    if (el.previousElementSibling) {
      el.previousElementSibling.focus()
    }
  }
  // 右键 
  else if (e.key === &#39;ArrowRight&#39;) {
    if (el.nextElementSibling) {
      el.nextElementSibling.focus()
    }
  }
  // 上键 
  else if (e.key === &#39;ArrowUp&#39;) {
    if (Number(state.confirmInput[index]) * 1 < 9) {
      state.confirmInput[index] = (Number(state.confirmInput[index]) * 1 + 1).toString()
    }
  }
  // 下键  
  else if (e.key === &#39;ArrowDown&#39;) {
    if (Number(state.confirmInput[index]) * 1 > 0) {
      state.confirmInput[index] = (Number(state.confirmInput[index]) * 1 - 1).toString()
    }
  }
}
// @keyup的处理方法
const confirmKeyUp = (e) => {
  var index = e.target.dataset.index * 1;
  // 如果为最后一个框,则输入框全部失焦
  if (index === 5) {
    if (state.confirmInput.join("").length === 6) {
      document.activeElement.blur();
    }
  }
}
// 重新输入
const reset = () => {
  state.disabledConfirm = true;
  state.tipContent = "请告知客户输入6位数字密码,输入完毕后,点击回车确认。";
  state.input = ["", "", "", "", "", ""];
  state.confirmInput = ["", "", "", "", "", ""];
  state.disabledInput = [false, false, false, false, false, false];
  state.disabledConfirmInput = [false, false, false, false, false, false];
  // 等待dom渲染完成,在执行focus,否则无法获取到焦点
  nextTick(() => {
    firstinput.value.focus();
  });
}
// 确认修改
const reConfirm = () => {
  ElMessageBox.confirm(
    &#39;是否确定修改?&#39;,
    &#39;温馨提示&#39;,
    {
      confirmButtonText: &#39;确定&#39;,
      cancelButtonText: &#39;取消&#39;,
      type: &#39;warning&#39;,
    }
  )
    .then(() => {
      // 此处调修改支付密码接口
      ElMessage({
        type: &#39;success&#39;,
        message: &#39;修改成功!&#39;,
      })
    })
    .catch(() => {
      ElMessage({
        type: &#39;info&#39;,
        message: &#39;已取消修改!&#39;,
      })
    })
}
</script>
<style lang="scss" scoped>
.input-box {
  .input-content {
    width: 512px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    input {
      color: inherit;
      font-family: inherit;
      border: 0;
      outline: 0;
      border-bottom: 1px solid #919191;
      height: 60px;
      width: 60px;
      font-size: 44px;
      text-align: center;
    }
  }
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    appearance: none;
    margin: 0;
  }
}
.noActive {
  color: #fff !important;
  border-width: 0px !important;
  background-color: #ccc !important;
}
.active {
  color: #fff !important;
  border-width: 0px !important;
  background-color: #67c23a !important;
}
</style>

2. 문제 분석

1. 질문: 암호문을 표시하는 방법과 각 상자에 1자리만 입력할 수 있나요?

비밀번호를 입력하려면 입력창 유형을 "비밀번호"로 설정하기만 하면 됩니다. 각 상자에 1자리만 입력할 수 있다는 점을 이해하려면 입력 상자의 maxlength 속성만 사용하는 효과가 완벽하지 않으며 제한할 수 없는 상황이 있을 수 있습니다. @input 이벤트입니다. 1보다 크면 nextElementSibling.focus()를 사용하여 다음 형제 요소에 커서를 놓습니다.

2. 질문: 입력 상자를 편집할 수 없고 반환할 수 없게 만드는 방법은 무엇입니까?

답변: @input 이벤트에서는 입력 상자의 비활성화 속성을 사용하며, 현재 입력 요소의 비활성화 속성을 true로 변경할 수 있습니다. 후속 획득 및 수정을 용이하게 하기 위해 입력 상자의 비활성화된 속성 값을 배열에 저장합니다.

3. 질문: 두 번 입력한 비밀번호의 일관성을 확인하는 방법은 무엇인가요?

답변: 가장 간단한 for 루프는 입력 비밀번호 배열과 확인 비밀번호 배열을 순회하고 해당 요소 값을 하나씩 비교하여 동일하지 않으면 동일하지 않으며 전체 함수의 실행을 종료하는 데 사용됩니다. 반품을 통해;.

4. 질문: 회사에서 키보드 키를 제한해야 하는 경우 어떻게 해야 합니까?

답변: @keydown 또는 @keyup 이벤트를 입력 상자에 추가하고 콜백 내부의 키를 판단하여 다양한 키에 대해 일부 비즈니스 처리를 수행할 수 있습니다.

위 내용은 vue3에서 6자리 결제 비밀번호 입력란을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제