基于element 实现input框输入金额显示千分位
通过el-input组件实现输入金额就能显示千分位,比较方便项目上遇到金额的地方,直接可以全局替换我们的input
html页面代码
mian.js全局引入这个组件,这样方便替换
import GalaxyNumberInput from '@/views/accountYx/components/drop/GalaxyNumberInput'
Vue.component('galaxy-number-input', GalaxyNumberInput)
代码里直接引用
<el-table-column prop="availableAmount" label="合同可付款金额" min-width="150" align="right" header-align="center">
<template slot-scope="scope">
<galaxy-number-input style="width:100%;margin:6px 0" :min="0" v-model="scope.row.availableAmount" :precision="2" :controls="false" size="mini" disabled />
</template>
</el-table-column>
input组件代码
<template>
<el-input
class="galaxy-num-input"
v-model="displayValue"
:size="size"
:clearable="clearable"
:disabled="disabled"
:placeholder="placeholder"
@change="changeInput"
@blur="onBlur"
@focus="focus">
</el-input>
</template>
<script>
export default {
props:{
value:{
type:[Number,String],
default:""
},
min:{
type:Number,
default:-999999999999999
},
max:{
type:Number,
default:999999999999999
},
precision:{
type:Number,
default:2
},
size:{
type:String,
default:"",
},
disabled:{
type:Boolean,
default:false
},
clearable:{
type:Boolean,
default:true
},
placeholder: {
type:String,
default:"",
}
},
data(){
return {
displayValue:"",
}
},
watch:{
value(){
this.displayValue = this.format(this.value);
},
displayValue(){
}
},
mounted(){
this.displayValue = this.format(this.value);
},
methods:{
format (val) {
if(this.checkRates(val)){
return Number(this.th2Num(val)).toFixed(this.precision).replace(/\B(?=(\d{3})+(?!\d))/g,',');
}else{
return "";
}
},
checkRates(str){
if(str===null||str===undefined){
return false
}else{
let numStr = str.toString().trim().replace(/,/g, "",)
var re = /^([0-9]+\.?[0-9]*|-[0-9]+\.?[0-9]*)$/;
return re.test(numStr);
}
},
th2Num(str){
if(str===null||str===undefined||str===""){
return 0;
}else{
return Number(str.toString().trim().replace(/,/g, "",));
}
},
onBlur(){
this.changeInput(this.displayValue);
},
changeInput(val){
console.log(val,"hhhhhhhhhhhhhhhhh")
const {min,max} = this.$props;
let num = Number(val.trim().replace(/,/g, ""));
if(!this.checkRates(val)){
this.displayValue = "";
}else{
if(num<min){
num = min;
}
if(num>max){
num = max;
}
}
this.displayValue = this.format(num);
this.$emit("input",Number(num.toFixed(this.precision)));
this.$emit("change",Number(num.toFixed(this.precision)));
},
focus(){
this.$emit("focus");
},
},
}
</script>
<style lang="scss" scoped>
.galaxy-num-input /deep/ .el-input__inner{
text-align: center !important;
}
</style>