input框仅允许输入大于0的浮点数 2位小数(vue3)

364 阅读1分钟
<input
  type="text"
  v-model="inputValue"
  @input="inputPrice"
  @change="changePrice"
/>

const inputValue = ref("");

const inputPrice = (e: any) => {
  let value = e.target?.value;
  value = value.replace(/\u3002/g, "."); // 测试发现按中文逗号没动静,替换成点
  value = Array.from(value.match(/^\d+(?:\.\d{0,2})?/) || [])[0] || ""; //只能输入2位小数

  // 不能连续0开头/大于0的不能0开头 0099、000.999
  const reg = /^(0+)/g;
  value = value.replace(reg, "0"); // 先全部替换成一个0
  if (value.length > 1) { // 再如果是011、04的话,0替换''
    if (!value.includes("0.")) { // 有一个例外:0.1、0.0的话,所有0都会变'',不希望这样,所以要排除在外
      value = value.replace(reg, "");
    }
  }
  inputValue.value = value;
};

const changePrice = (e: any) => {
  if (+e.target?.value === 0) { // +0.00 === 0
    inputValue.value = "";
  }
};