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