最近在自学vue3相关的知识,昨天用vue3的watch监听实现了满足日常各种情况的金额输入框,详情可见
今天又学习了vue3封装组件相关知识,就把昨天的金额输入框封装成了一个组件,实现效果如下:
代码如下:
子组件
<template>
<el-input v-model="a" @blur="amountBlur" @focus="amountFocus" :placeholder="placeholder"></el-input>
</template>
<script setup lang="ts">
import {ref, watch} from 'vue'
import common from "../utils/common";
const props = defineProps({
modelValue: {
type: String,
default: ''
},
precision: {
type: Number,
default: 2
},
unit: {
type: Boolean,
default: true
},
maxlength: {
type: Number||String,
default: 10
},
placeholder: {
type: String,
default: '请输入金额'
}
})
const emits = defineEmits(['update:modelValue'])
let a = ref(props.modelValue+'');
let temp = 'temp'
const amountFocus = function () {
a.value = temp
temp = 'temp'
}
const amountBlur = function () {
temp = a.value;
a.value = common.amountFormat(a.value,props.precision,props.unit);
}
amountBlur()
watch(a,(newVal, oldValue) => {
// 临时变量不为'temp'时不启动监听
if(temp !== 'temp') return
// pc端中文输入法'。' ==> '.'
let newStr = (newVal+'').replace('。','.').replace(/[^0-9.]/g,'')
let oldStr = oldValue+''
// .xxx ==> 0.xxx
if(newStr.startsWith('.')) {
newStr = '0.' + newStr.slice(1)
}
// 0xxx ==> xxx
if(newStr.startsWith('0') && newStr.length>1 && !newStr.slice(1).startsWith('.')) {
newStr = newStr.slice(1)
}
// 限制小数点数量、小数点后两位小数、金额字符串总长度
if(newStr.split('.').length>2 || (newStr.split('.').length==2 && newStr.split('.')[1].length>props.precision) || newStr.length>Number(props.maxlength)){
newStr = oldStr;
}
a.value = newStr
emits("update:modelValue", newStr)
})
</script>
这里要注意vue3中获取props
及emits
的方式以及子组件修改值后v-model的值要通过update:modelValue
方法传递给父组件
父组件引用
<template>
<div>
<amount-input v-model="amount"></amount-input>
<el-button type="primary" @click="confirm" style="margin-top: 20px">确定</el-button>
</div>
</template>
<script setup lang="ts">
import AmountInput from '../../components/AmountInput.vue'
import {ref} from "vue";
let amount = ref('');
const confirm = function () {
console.log(amount.value)
}
</script>
下面是amountFormat今天标准格式化方法的实现,昨天已经发了,今天再发一遍吧
// common.js
/**
* 金额格式化
* @param amount 金额String||Number
* @param precision 小数位数Number(0-20)
* @param unit 是否带单位Boolean
* @returns {string}
*/
amountFormat: function(amount, precision, unit) {
if(amount == '') amount = '0'
precision = precision > 0 && precision <= 20 ? precision : 2;
amount = parseFloat((amount + "").replace(/[^\d\.-]/g, "")).toFixed(precision) + "";
let l = amount.split(".")[0].split("").reverse();
let r = amount.split(".")[1];
let t = "";
for (let i = 0; i < l.length; i++) {
t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
}
if(unit) {
return t.split("").reverse().join("") + "." + r + '元';
} else {
return t.split("").reverse().join("") + "." + r;
}
}
成长是一个不断学习的过程,愿你我共同进步!