先创建一个regular.js文件 里面封装脱敏的方法
const idCard = /(\d{4})\d*([0-9a-zA-Z]{4})/
const phone = /^(\d{3})\d{4}(\d{4})$/
const name2 = /^(.).+$/
const name3 = /^(.+).(.)$/
function tmIdCard(val) {
return val.replace(idCard, "$1******$2")
}
function tmPhone(val) {
return val.replace(phone, "$1******$2")
}
function tmName(val) {
if (val && val.length == 2) {
return val.replace(name2, "$1*")
} else if (val && val.length > 2) {
return val.replace(name3, "$1*$2")
} else {
return val
}
}
export default {
//正则
tmIdCard,
tmPhone,
tmName,
}
然后再main.js中引入
import regular from './directive/regular'; //封装脱敏方法
Vue.prototype.regular = regular; //封装公用脱敏方法
页面中使用
<template slot-scope="scope" slot="idCard">
<span>{{ regular.tmIdCard(scope.row.idCard) }}</span>
</template>
<template slot-scope="scope" slot="userName">
<span>{{ regular.tmName(scope.row.userName) }}</span>
</template>
封装前后代码对比
封装前
<template slot-scope="scope" slot="idCard">
<span>{{
scope.row.idCard.replace(/(\d{4})\d*([0-9a-zA-Z]{4})/, "$1******$2")
}}</span>
</template>
<template slot-scope="scope" slot="userName">
<span v-if="scope.row.userName && scope.row.userName.length > 2">{{
scope.row.userName.replace(/^(.+).(.)$/, "$1*$2")
}}</span>
<span v-if="scope.row.userName && scope.row.userName.length == 2">{{
scope.row.userName.replace(/^(.).+$/, "$1*")
}}</span>
<span v-if="!scope.row.userName">{{ scope.row.userName }}</span>
</template>
封装后
<template slot-scope="scope" slot="idCard">
<span>{{ regular.tmIdCard(scope.row.idCard) }}</span>
</template>
<template slot-scope="scope" slot="userName">
<span>{{ regular.tmName(scope.row.userName) }}</span>
</template>
代码简洁很多 而且很好维护 以后就算有什么 金额 邮箱啥的 直接在regular里面加代码就行