el-input,金额千分符自动转换
1. 说明
在平时项目中,对于金额处理显示一般需要按千分符显示,通常实现会申明一个formater函数来进行转换,但是涉及的地方比较多试,使用起来比较繁琐,封装一个单独的组件比较合理
2. 实现组件代码
- ElMoneyInput.vue
<template><div :style="{'background-color': disabled ? 'transparent' : '#fff'}"><span class="money-input" v-if="!isInput" @click="focusHanle" :disabled="disabled" :value="viewValue">{{ viewValue }}</span><el-input ref="moneyInput" v-else v-bind="$attrs" :value="value" @input="handlerChange" @blur="handlerBlur" autofocus onkeypress="if(event.keyCode == 13) return false;"/></div>
</template>
<script>
export default {name: 'ElMoneyInput',inheritAttrs: false,model: {prop: "value",event: "input"},props: {value: {type: String,default: ""},disabled:{type:Boolean,default:false},rules: {type: Object,default: () => {}}},watch: {value(val, old) {if (val !== old) {this.init()}}},mounted() {this.init()},data() {return {isEdit: true,isInput: false,viewValue: ''};},methods: {init() {if (!this.isInput) {this.viewValue = this.formatMoney(this.value || 0)this.$emit('input', this.blurformat(this.value || 0))}},focusHanle() {if (this.disabled) returnthis.isInput = !this.isInputthis.$emit('input', this.blurformat(this.value || 0))this.$nextTick(() => {this.$refs.moneyInput.focus()})},formatMoney(cellValue, num = 2) {if (isNaN(cellValue)) {return ""}if (cellValue === 0) {return '0.00';}return this.$Utils.formatMoney(cellValue, num);},format(v) {return (`${v}`.match(/([\d\.]+)/) || "")[0];},blurformat(v) {return v ? Number.parseFloat(v).toFixed(2) : "";},handlerChange(v) {this.$emit('input', v)},handlerBlur() {this.isInput = false;this.$emit('input', this.blurformat(this.value))this.viewValue = this.formatMoney(this.value)},// handleFocus() {// this.isInput = true;// this.$emit('input', this.blurformat(this.value))// }}
};
</script>
<style lang="less">
.span-input{display: inline-block;width: 100%;height:28px;
}
.money-input {position: relative;font-size: 14px;display: inline-block;height: 32px;line-height: 32px;background: transparent !important;cursor: text !important;background-color: #FFF;background-image: none;border-radius: 4px;border: 1px solid #DCDFE6;-webkit-box-sizing: border-box;box-sizing: border-box;color: #606266;display: inline-block;font-size: inherit;outline: 0;padding: 0 15px;-webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);transition: border-color .2s cubic-bezier(.645,.045,.355,1);width: 100%;.el-input__inner {background: transparent !important;cursor: text !important;background-color: #FFF;background-image: none;border-radius: 4px;border: 1px solid #DCDFE6;-webkit-box-sizing: border-box;box-sizing: border-box;color: #606266;display: inline-block;font-size: inherit;height: 40px;line-height: 40px;outline: 0;padding: 0 15px;-webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);transition: border-color .2s cubic-bezier(.645,.045,.355,1);width: 100%;}
}
</style>