vue封装正则脱敏方法,可直接用到项目中

先创建一个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里面加代码就行

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值