<template>
<div :class="classComputed">
<input
ref="input"
style="text-align: right;"
class="el-input__inner"
:placeholder="placeholder"
:value="formatValue"
:disabled="disabled"
@input="updateValue($event.target.value)"
@blur="onBlur"
@focus="selectAll"
>
</div>
</template>
<script>
import accounting from 'accounting'
export default {
props: {
value: {
type: [String, Number],
default: '',
desc: '数值'
},
disabled: {
type: Boolean,
default: false
},
symbol: {
type: String,
default: '',
desc: '货币标识符'
},
placeholder: {
type: String,
default: '',
desc: '货币标识符'
},
precision: {
type: Number,
default: 2,
desc: '小数位'
},
min: {
type: [String, Number],
default: '',
desc: '最小值'
},
elvalue: [String, Number]
},
data () {
return {
focused: false
}
},
computed: {
classComputed () {
let str = 'el-input el-input--mini'
if (this.disabled) {
str = `${this.className} ${str} is-disabled`
}
return str
},
formatValue () {
if (this.focused) {
let formatValue
if (this.value === '' || this.value === undefined) {
formatValue = ''
} else if (this.value === '-') {
formatValue = '-'
} else {
formatValue = accounting.unformat(this.value)
}
return formatValue
} else {
if (this.value === 0) {
return accounting.formatMoney(this.value, this.symbol, this.precision)
} else if (
this.value === '' ||
this.value === null ||
this.value === undefined
) {
return ''
} else {
return accounting.formatMoney(this.value, this.symbol, this.precision)
}
}
}
},
methods: {
updateValue (value) {
let formatValue
if (value === '' || value === undefined) {
formatValue = ''
} else if (value === '-') {
formatValue = '-'
} else {
formatValue = accounting.unformat(value)
}
this.$emit('input', formatValue)
},
onBlur () {
this.focused = false
this.$emit('blur', event)
this.dispatch('ElFormItem', 'el.form.blur', [this.value])
},
selectAll (event) {
this.focused = true
setTimeout(() => {
event.target.select()
}, 0)
},
dispatch (componentName, eventName, params) {
var parent = this.$parent || this.$root
var name = parent.$options.componentName
while (parent && (!name || name !== componentName)) {
parent = parent.$parent
if (parent) {
name = parent.$options.componentName
}
}
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params))
}
}
}
}
</script>