僅個人經驗,希望能幫到有需要的人。
第一次寫 就話不多說了直接上代碼。
<el-input @keyup.native="proving(index)" v-model="item.Price"></el-input>
// 只能輸入數字且只有一位小數 proving(e) { // this.form.skus[e].Price 是input的值 // 先把非數字的都替換掉,除了數字和. this.form.skus[e].Price = this.form.skus[e].Price.replace(/[^\d.]/g, ''); // 必須保證第一個為數字而不是. this.form.skus[e].Price = this.form.skus[e]Price.replace(/^\./g, ''); // 保證只有出現一個.而沒有多個. this.form.skus[e].Price = this.form.skus[e].Price.replace(/\.{2,}/g, ''); // 保證.只出現一次,而不能出現兩次以上 this.form.skus[e].Price = this.form.skus[e].Price.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); let index = -1 for (let i in this.form.skus[e].Price) { if (this.form.skus[e].Price[i] === '.') { index = i } if (index !== -1) { if (i - index > 1) { this.form.skus[e].Price = this.form.skus[e].Price.substring(0, this.form.skus[e].Price.length - 1) } } } },