vue实现输入金额时
Vue实现输入金额时的常见需求
在Vue中实现金额输入功能时,通常需要考虑以下方面:
金额输入框的基本实现
使用v-model绑定输入值,结合@input事件处理金额格式化:
<template>
<input
v-model="amount"
@input="formatAmount"
type="text"
/>
</template>
<script>
export default {
data() {
return {
amount: ''
}
},
methods: {
formatAmount() {
this.amount = this.amount.replace(/[^\d.]/g, '')
}
}
}
</script>
金额格式化处理
添加千分位分隔符和限制小数位数:
methods: {
formatAmount() {
let value = this.amount.replace(/[^\d.]/g, '')
const parts = value.split('.')
// 处理整数部分
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
// 限制小数位数
if (parts.length > 1) {
parts[1] = parts[1].slice(0, 2)
}
this.amount = parts.join('.')
}
}
金额输入验证
添加金额有效性验证:
methods: {
validateAmount() {
const num = parseFloat(this.amount.replace(/,/g, ''))
if (isNaN(num)) {
this.error = '请输入有效金额'
return false
}
if (num <= 0) {
this.error = '金额必须大于零'
return false
}
this.error = ''
return true
}
}
自定义金额输入组件
创建可复用的金额输入组件:
<template>
<div class="amount-input">
<input
:value="formattedValue"
@input="handleInput"
@blur="handleBlur"
placeholder="0.00"
/>
<div v-if="error" class="error">{{ error }}</div>
</div>
</template>
<script>
export default {
props: {
value: Number
},
data() {
return {
error: ''
}
},
computed: {
formattedValue() {
return this.value ? this.value.toLocaleString() : ''
}
},
methods: {
handleInput(e) {
const rawValue = e.target.value.replace(/,/g, '')
const num = parseFloat(rawValue)
if (!isNaN(num)) {
this.$emit('input', num)
}
},
handleBlur() {
if (this.value === undefined || this.value === null) {
this.error = '请输入金额'
}
}
}
}
</script>
输入框的增强功能
添加货币符号和更好的用户体验:
<template>
<div class="currency-input">
<span class="symbol">¥</span>
<input
v-model="displayValue"
@focus="handleFocus"
@blur="handleBlur"
/>
</div>
</template>
<script>
export default {
props: {
value: Number
},
data() {
return {
displayValue: ''
}
},
watch: {
value: {
immediate: true,
handler(newVal) {
this.displayValue = newVal ? newVal.toFixed(2) : ''
}
}
},
methods: {
handleFocus() {
this.displayValue = this.value ? this.value.toString() : ''
},
handleBlur() {
const num = parseFloat(this.displayValue)
if (!isNaN(num)) {
this.$emit('input', parseFloat(num.toFixed(2)))
}
}
}
}
</script>
移动端优化
针对移动设备优化金额输入:
<template>
<input
v-model="amount"
type="tel"
pattern="[0-9]*"
inputmode="numeric"
@input="formatMobileAmount"
/>
</template>
<script>
export default {
methods: {
formatMobileAmount() {
this.amount = this.amount.replace(/[^\d]/g, '')
if (this.amount.length > 2) {
this.amount = `${this.amount.slice(0, -2)}.${this.amount.slice(-2)}`
}
}
}
}
</script>
这些方法可以根据具体需求组合使用,实现不同场景下的金额输入功能。对于更复杂的金融应用,可能需要考虑集成第三方库如currency.js或accounting.js来处理更专业的货币格式化需求。







