el-input 实现手机号、身份证号等输入动态脱敏
具体实现输入的手机号只显示前后四位,中间由*号代替,右侧有图标控制显隐脱敏数据
参考文章: juejin.cn/post/710937…
<el-form-item label="联系方式" prop='planCarNumber'>
<el-input
:placeholder="'请输入'"
v-model="normalPhone"
type="text"
@input.native="desenInputText($event, 'normalPhone', 'planCarNumber')"
:disabled="rules.numberPeople === undefined? true: false">
<template slot="suffix">
<span class="show-pwd" @click.stop="showPwd('normalPhone', 'planCarNumber')" style="background:rgba(255,255,255,0)">
<svg-icon :icon-class="!isShowPhone ? 'eye-open' : 'eye-close'" />
</span>
</template>
</el-input>
</el-form-item>
// 是否脱敏
showPwd(showValue, trueValue) {
this.isShowPhone = !this.isShowPhone
if (!this.isShowPhone) {
this[showValue] = this.formData[trueValue]
} else {
this[showValue] = this.desenText(this.formData[trueValue])
}
},
//输入框动态脱敏 showValue 掩码展示数据, trueValue实际输入数据
desenInputText(e, showValue, trueValue) {
const ind = e.target.selectionStart - 1;
let value = this.formData[trueValue] || ''
const normalPhone = this[showValue];
const isAdd = normalPhone.length > value.length;
const num = Math.abs(value.length - normalPhone.length);
if (isAdd) {
value =
value.slice(0, ind-num+1) +
normalPhone.slice(ind-num+1,ind+1) +
value.slice(ind-num+1);
} else {
value = value.slice(0, ind + 1) + value.slice(ind + num + 1);
}
this.formData[trueValue] = value;
this[showValue] = this.desenText(value);
this.$nextTick(() => {
const elem = e.target;
if (elem.setSelectionRange) {
// 标准浏览器
elem.setSelectionRange(ind + 1, ind + 1);
} else {
// IE9-
const range = elem.createTextRange();
range.moveStart('character', ind + 1);
range.moveEnd('character', ind + 1);
range.select();
}
});
},
desenText(str) {
let res = str;
const len = str.length;
let pre4 = '';
let last4 = '';
pre4 = str.slice(0, 4);
last4 = str.slice(Math.max(len - 4, 4));
const star = Math.max(0, len - 8);
res = pre4 + '*'.repeat(star) + last4;
return res;
},
```