vue input数据动态脱敏

  页面中放两个输入框,一个绑定真实数据、一个绑定脱敏数据,仅展示脱敏数据。

 <van-field
      v-model="person.cardNo"
      v-show="false"
      name="证件号码"
      label="证件号码"
      left-icon="coupon"
      placeholder="证件号码"
      required
    />
    <van-field
      v-model="person.cardNoShow"
      name="证件号码"
      label="证件号码"
      left-icon="coupon"
      placeholder="证件号码"
      @input="desenInputText($event, person, 'cardNo', 'cardNoShow', 4, 6)"
      required
    />

  脱敏方法,以光标为界,分输入和删除两种情况处理:

  desenText(str, preNum, endNum) {
      let res = str || "";
      const len = str.length;
      let pre = "";
      let last = "";
      pre = str.slice(0, preNum);
      last = str.slice(Math.max(len - endNum, preNum));
      const star = Math.max(0, len - preNum - endNum);
      res = pre + "*".repeat(star) + last;
      return res;
    },

    /**输入框动态脱敏,
     * el 承载真实数据与脱敏数据的对象
     * key 真实数据的 key
     * showKey 脱敏数据的 key
     * **/
    desenInputText(e, el, key, showKey, preNum, endNum) {
      if (!el) return;
      const ind = e.target.selectionStart - 1;
      let value = el[key];
      const showValue = el[showKey];
      const isAdd = showValue.length > value.length;
      const num = Math.abs(value.length - showValue.length);
      if (isAdd) {
        value =
          value.slice(0, ind - num + 1) +
          showValue.slice(ind - num + 1, ind + 1) +
          value.slice(ind - num + 1);
      } else {
        value = value.slice(0, ind + 1) + value.slice(ind + num + 1);
      }
      el[key] = value;
      el[showKey] = this.desenText(value, preNum, endNum);
      // 光标复位
      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();
        }
      });
    },

 

posted @ 2022-11-14 17:15  牛有肉  阅读(415)  评论(0编辑  收藏  举报