vue 手写组件隐藏手机号和身份证号,并可以复制


<template >
  <div>
    <span>{{ value }}</span>
    <i v-if="value != '' " @click="copyValue()" style="margin-left: 10px; color: blue; cursor:pointer" class="el-icon-copy-document"/>
  </div>
</template>

<script>

export default {
  data() {
    return {
      value: this.changeValue()
    }
  },
  props: {
    replaceValue: {
      type: '',
      default: ""
    },
    replaceType: {
      type: '',
      default: "phone"
    }
  },
  methods:{
    // 复制功能
    copyValue(){
      let content = this.replaceValue
      if (window.clipboardData) {
        window.clipboardData.setData('text', content);
      } else {
        (function (content) {
          document.oncopy = function (e) {
            e.clipboardData.setData('text', content);
            e.preventDefault(); //取消事件的默认动作
            document.oncopy = null;
          }
        })(content);
        document.execCommand('Copy');
        this.$message({
          message: '复制成功',
          type: 'success'
        })
      }
    },
    changeValue(){
        if(this.replaceValue){
          if(this.replaceType == " 手机号字段 "){ //备注: 要和使用组件的地方的字段相对应才能解析
            return this.replaceValue.replace(/^(.{3}).*(.{4})$/,'$1****$2');
          }else if(this.replaceType == " 身份证号码字段 "){//备注: 要和使用组件的地方的字段相对应才能解析
return this.replaceValue.replace(/^(.{6})(?:\w+)(.{4})$/,'$1********$2'); } }else{ return ""; } }, } } 
</script>

  

在 vue 项目的 components 里创建一个文件夹和一个 index.vue 文件,然后把上面的代码复制进去就行。

@mousemove="onmouseenters" //事件冒泡处理其他操作
      @mouseout="onmouseleaves"
      v-if="!valueStatus" // 是否隐藏号码

 

 

 

 在 main.js 全局挂载

// 脱敏组件
import TransTo from '@/components/Transitive'
Vue.component('TransTo', TransTo)

  

最后是 使用方法

// 手机号的使用

<TransTo :replaceValue="scope.row.phone" :key="Math.random()" />

//身份证的使用

<TransTo :replaceValue="scope.row.cardNo" replaceType="cardNo" :key ="Math.random()" />

//注意: :key ="Math.random()" 这一行是必须写的,因为不写会导致拿不到正确的数据,或者说是数据没有更新过来

  // 备注:如果出现报错: Cannot read properties of undefined (reading 'key') 可以通过格式化解决,即去除小数点解决

代码:

:key="Math.random().toFixed(0) * 1"

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM