全网最简单的vue验证码输入框组件

先上图在这里插入图片描述
要实现一个类似于这样的输入框,而且有几个页面都需要类似的输入框(输入身份证后四位/输入支付密码),就准备撸一个小组件。

原理

在一个输入框中输入一串字符串,然后根据下标index分别填入框里,为了代码的可读性,我这里框就用ul,li来写

子组件

<template>
  <div>
    <label for="code">
      <ul class="code-box">
        <li class="code-number" v-for="(item, index) in length" :key="index">
          {{ code[index] }}
        </li>
      </ul>
    </label>
    <input
      class="code-input"
      v-model="code"
      :maxlength="length"
      type="number"
      id="code"
      @keyup.13="next()"
    />
  </div>
</template>

<script>
export default {
  name: "CodeInput",
  props: {
    length: {
      type: Number,
      default: 6
    }
  },
  data() {
    return {
      code: ""
    };
  },
  methods: {
    getCode() {
      return this.code;
    },
    next() {
      this.$emit("func", this.code);
    }
  }
};
</script>
<style scoped>
.code-box {
  border-radius: 8px;
  border: 1px solid #cccccc;
  display: inline-flex;
}
.code-number {
  width: 56px;
  height: 58px;
  border-right: solid #cccccc 1px;
  text-align: center;
  font-size: 30px;
  color: red;
}
.code-number:last-child {
  border-right: 0;
}
.code-input {
  height: 0.44rem;
  position: fixed;
  outline: none;
  color: transparent;
  text-shadow: 0 0 0 transparent;
  width: 300%;
  margin-left: 100%;
}
button {
  width: 100px;
  height: 60px;
}
</style>


父组件

<template>
  <div>
    <security-code v-model="code" v-on:func="show"></security-code>
  </div>
</template>
<script>
import securityCode from "../components/password";
export default {
  components: { securityCode },
  data() {
    return {
      code: ""
    };
  },
  methods: {
    show() {
      console.log(this.code);
      this.$router.push({ path: "/" });
    }
  }
};
</script>
<style lang="less" scoped></style>

注意点

label属性:html的label属性可以根据input的id扩大input的点击面积。

@keyup.13=“next()”:这一句是指手机键盘的回车/确定/前进键触发 的事件

子组件input的位置:我是通过绝对定位使他不在我可视位置上,不能让他display:none

附加:因为一般父子组件的style都是设置了scoped,如果想对设置了scoped的子组件里的元素进行控制可以使用 ’>>>’ 或者 ’deep’,这个自己百度很多方法

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值