el-input保留两位小数

1,348 阅读1分钟

只能输入数字

<el-input size="mini"  v-model="scope.row.a" oninput="value=value.replace(/[^\d]/g,'')"></el-input>

话不多说,上代码

<template>
  <div>
    <el-table ref="singleTable" :data="tableData" highlight-current-row style="width: 100%">
      <el-table-column property="a" label="一月" width="120">
        <template slot-scope="scope">
          <el-input
            size="medium"
            v-model.trim="scope.row.a"
            placeholder="提取金额"
            @keyup.native="keyupEvent($event,scope.row.id,'a')"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column property="b" label="二月" width="120">
        <template slot-scope="scope">
          <el-input
            size="medium"
            v-model.trim="scope.row.b"
            placeholder="提取金额"
            @keyup.native="keyupEvent($event,scope.row.id,'b')"
          ></el-input>
        </template>
      </el-table-column>
    </el-table>
    <el-button @click="close"></el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        { id: 1, a: 1, b: 1 },
        { id: 2, a: 2, b: 2 }
      ],
    };
  },
  methods: {
    close() {
      console.log(this.tableData)
    },
    keyupEvent(e, id,name) {
      e.target.value = e.target.value.replace(/[^\d.]/g, "");
      e.target.value = e.target.value.replace(/\.{2,}/g, ".");
      e.target.value = e.target.value.replace(/^\./g, "0.");
      e.target.value = e.target.value.replace(
        /^\d*\.\d*\./g,
        e.target.value.substring(0, e.target.value.length - 1)
      );
      e.target.value = e.target.value.replace(/^0[^\.]+/g, "0");
      e.target.value = e.target.value.replace(/^(\d+)\.(\d\d).*$/, "$1.$2");
      this.tableData.map(item => {
        if (id === item.id) {
          item[name] = e.target.value;
          return false;
        }
      });
    }
  }
};
</script>