实现的效果展示,可以是前缀单位,也可以是后缀单位。实现的思路就是动态修改伪元素 ::before 和 ::after 的 content值
实现二次封装数字框的代码如下:
<template>
<el-input-number
ref="inputNumber"
v-model="inputValue"
clearable
:controls="false"
:data-content="showPendAttr.value"
v-bind="$attrs"
class="c-input-number c-input-number-pend"
:class="{
'pend-before': showPendAttr.pend === pendEnum.PRE,
'pend-after': showPendAttr.pend === pendEnum.AFTER
}"
>
</el-input-number>
</template>
<script lang="ts" setup>
import { ref, computed } from "vue";
enum pendEnum {
PRE = "pre", // 前置单位
AFTER = "after" // 后置单位
}
type Props = {
modelValue: any;
pendAttr?: { [key: string]: any };
};
const props = withDefaults(defineProps<Props>(), {
modelValue: ""
});
const emit = defineEmits(["update:modelValue", "search"]);
const inputNumber = ref();
// 处理input输入框双向绑定
const inputValue = computed({
get: () => {
return props.modelValue;
},
set: (val: any) => {
emit("update:modelValue", val);
}
});
// 这里是处理pendAttr参数的,用新传入的pendAttr的参数替换默认的
const showPendAttr = computed(() => {
let defaultPendAttr: { [key: string]: any } = { pend: pendEnum.PRE, value: ""};
defaultPendAttr = { ...defaultPendAttr, ...props.pendAttr };
return defaultPendAttr;
});
defineExpose({
inputNumber
});
</script>
<style lang="scss" scoped>
.c-input-number {
position: relative;
}
.c-input-number-pend::before,
.c-input-number-pend::after {
position: absolute;
top: 50%;
z-index: 1;
display: inline-block;
font-size: 13px;
text-align: center;
transform: translateY(-50%);
}
.pend-before::before {
left: 12px;
content: attr(data-content);
}
.pend-after::after {
right: 12px;
content: attr(data-content); // 可以获取自定义传值实现动态修改content
}
// 以下代码是解决单位重叠
.pend-before {
:deep(.el-input__wrapper) {
padding-left: 32px !important;
}
}
.pend-after {
:deep(.el-input__wrapper) {
padding-right: 32px !important;
}
}
</style>
使用:
<el-form-item label="入款金额:" prop="money">
<c-input-number
v-model="configForm.money"
:min="0"
:pendAttr="{ pend: 'pre', value: '$' }"
placeholder="请输入入款金额"
style="width: 300px"
</c-input-number>
</el-form-item>