vue,input,只能输入整数或者小数

2019-11-22  本文已影响0人  Wrestle_Mania
<template lang="html">
  <div class="">
    <input v-model="num" @keyup="numKeyUp" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      num: ""
    };
  },
  computed: {},
  created() {},
  mounted() {},
  methods: {
    numKeyUp() {
      let lastStr = this.num[this.num.length - 1];
      let splitArr = this.num.split(".");
      if (lastStr === ".") {
        // 不能写连续的点、首位不能是点
        if (splitArr.length > 2) splitArr.pop();
        this.num = splitArr[0] ? splitArr.join(".") : "";
      } else {
        if (this.num.includes(".")) {
          // 存在小数点,并且小数点后面输入的不是数字
          let lastStr = splitArr[1];
          let secondStr = parseFloat(lastStr);
          let tempStr = "";
          if (isNaN(secondStr)) {
            // 小数点后第一位不是数字,则清空
            tempStr = "";
          } else {
            if (secondStr.length !== lastStr.length) {
              let len = lastStr.length - 1;
              let bool = /\d$/.test(lastStr[len]);
              // 补零的操作,如果最后一位是数字的话补完整的0,如果不是的话,少补一个0
              tempStr = secondStr
                .toString()
                .padStart(bool ? lastStr.length : len, "0");
            }
          }
          this.num = splitArr[0] + "." + tempStr;
        } else {
          let tempNum = parseFloat(this.num);
          if (isNaN(tempNum)) {
            // 首次输入不是数字
            this.num = "";
          } else {
            this.num = tempNum.toString();
          }
        }
      }
    },
    doInput() {
      this.numKeyUp();
    }
  },
  watch: {},
  components: {}
};
</script>

<style lang="scss" scoped></style>

正则好像有更简洁的写法,明天继续优化下

上一篇下一篇

猜你喜欢

热点阅读