Skip to content

Commit

Permalink
optimize the inputNumber
Browse files Browse the repository at this point in the history
fixed bug
1. when setting the precision, inputNumer cannot input '.' bug
2. when setting  the precision, the cursor positoning bug
  • Loading branch information
mo.duan committed Sep 2, 2019
1 parent 6daad53 commit 5ece780
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
4 changes: 4 additions & 0 deletions examples/routers/input-number.vue
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@
:formatter="value => `${value}%`"
:parser="value => value.replace('%', '')"></InputNumber>
</div>
<div style="margin-top: 10px">
<InputNumber v-model="value4" style="width: 200px" :precision='2' ></InputNumber>
</div>
</div>
</template>
<script>
Expand All @@ -81,6 +84,7 @@
value1: 1800000,
value2: 55,
value3: 100,
value4 : null,
valueNull:null,
formatter: (value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','),
parser: (value) => value.replace(/\$\s?|(,*)/g, ''),
Expand Down
26 changes: 22 additions & 4 deletions src/components/input-number/input-number.vue
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
@blur="blur"
@keydown.stop="keyDown"
@input="change"
ref="precisionCursor"
@mouseup="preventDefault"
@change="change"
:readonly="readonly || !editable"
Expand Down Expand Up @@ -305,15 +306,24 @@
this.setValue(null);
return;
}
if (event.type == 'input' && val.match(/^\-?\.?$|\.$/)) return; // prevent fire early if decimal. If no more input the change event will fire later
if (event.type == 'input' && val.match(/^\-?\.?$|\.$/g)) return; // prevent fire early if decimal. If no more input the change event will fire later
val = Number(val);
//#fixed when setting the precision val, input point cannot show problem
const precision = this.precision;
let cacheVal = this.currentValue;
if( precision ){
const valMatchPointArr = (val+'').match(/\./g);
if( valMatchPointArr && valMatchPointArr.length >= 2 ){
cacheVal = this.currentValue + '.';
}
}
if (!isNaN(val)) {
val = Number(val);
if (!isNaN(val) ) {
this.currentValue = val;
this.setValue(val);
} else {
event.target.value = this.currentValue;
event.target.value = cacheVal;
}
},
changeVal (val) {
Expand All @@ -338,6 +348,14 @@
},
currentValue (val) {
this.changeVal(val);
//optimization - Solve the problem of cursor positioning inaccuracy
this.$nextTick(()=>{
if( this.precision ){
const currentValueLength = ( this.currentValue || 0 ).toString().length;
const precisionCursor = this.$refs.precisionCursor;
precisionCursor.selectionStart = precisionCursor.selectionEnd = currentValueLength;
}
});
},
min () {
this.changeVal(this.currentValue);
Expand Down

0 comments on commit 5ece780

Please sign in to comment.