金额格式化vue组件实现
// 金额格式化组件
/**
* 金额格式化组件
* 接入方法 <money-input v-model=""></money-input>
*/
Vue.component("money-input", {
template: '<input ref="money" :type="type" @input="input" v-model="money" @blur="setmoney" @focus="getmoney" />',
props: ["value"],
data() {
return {
money: "",
type: "text"
}
},
computed: {
},
watch: {
"value": "ajax_getmoney"
},
created() {
this.ajax_getmoney();
},
methods: {
ajax_getmoney() {
if (this.money !== this.value) {
this.money = this.value;
this.$nextTick(function () {
this.$refs.money.value = this.money_change(this.money);
});
}
},
input(e) {
this.$emit('input', this.money);
},
setmoney(e) {
this.type = "text";
this.$nextTick(function () {
e.target.value = this.money_change(e.target.value);
this.$emit('update:value', this.money);
});
},
getmoney(e) {
this.type = "number";
this.$nextTick(function () {
e.target.value = this.money;
});
},
money_change(val) {
if (val === "") {
return "";
}
val = val.toString().replace(/\$|\,/g, "");
if (isNaN(val)) {
val = "0";
}
let sign = (val == (val = Math.abs(val)));
val = Math.floor(val * 100 + 0.50000000001);
let cents = val % 100;
val = Math.floor(val / 100).toString();
if (cents < 10) {
cents = "0" + cents;
}
for (let i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
val = val.substring(0, val.length - (4 * i + 3)) + "," + val.substring(val.length - (4 * i + 3));
}
return (((sign) ? "" : "-") + val + "." + cents);
}
},
});
// 金额格式化组件
使用方式
html:
<money-input v-model="num"></money-input>
js:
data() {
return {
num: "12345"
}
}