避免 el-input 密码自动填充的实用方法

避免 el-input 密码自动填充的实用方法

在开发 Web 应用时,通常需要避免浏览器自动填充密码。以下是一些可行的解决方案,特别针对使用 Element UI 框架的 el-input 组件。

方法 1:设置随机的 nameautocomplete 属性

浏览器根据 name 属性来识别输入字段的类型,因此可以使用随机的 name 属性,并将 autocomplete 设置为 new-password

实现

<el-input
  type="password"
  :name="randomName"
  autocomplete="new-password"
  v-model="password">
</el-input>
export default {
  data() {
    return {
      password: '',
      randomName: `password_${Math.random().toString(36).substr(2, 9)}`
    };
  }
}

方法 2:使用隐藏的密码输入字段

通过在页面中添加一个隐藏的输入字段,可以避免自动填充密码字段。

实现

<el-input
  type="text"
  style="display: none;"
  autocomplete="username">
</el-input>
<el-input
  type="password"
  autocomplete="new-password"
  v-model="password">
</el-input>

方法 3:使用 meta 标签阻止密码管理器

在 HTML 中添加以下 meta 标签,可能会阻止某些密码管理器的自动填充功能。

实现

<meta name="disable-autofill" content="on">

方法 4:事件拦截

通过监听输入事件,可以在获取焦点时手动清除输入字段的内容。

实现

methods: {
  clearInput(event) {
    event.target.value = '';
  }
}
<el-input
  type="password"
  autocomplete="new-password"
  @focus="clearInput"
  v-model="password">
</el-input>

方法 5:动态改变 readonly 属性

通过设置 readonly 属性为true,可以避免一开始自动填充,在 mousedown 或 focus 事件触发时设置为 false ,允许输入

实现

          <el-input
            placeholder="密码"
            type="password"
            v-model="loginForm.userPwd"
            show-password
            @focus="passwordMousedownFun"
            @input="passwordInputFun"
            @mousedown.native="passwordMousedownFun"
            :readonly="passwordReadonly"
            id="passwordRef"
          >

      loginForm: {
        userName: "",
        userPwd: "",
        userRember: false,
      },

      passwordReadonly: true,

  watch: {
    loginForm: {
      handler: function (newValue, oldValue) {
        if (newValue.userPwd == "") {
          this.passwordReadonly = true;
          setTimeout(() => {
            this.passwordReadonly = false;
          }, 0);
        }
      },
      deep: true,
    },
  },


    passwordMousedownFun() {
      if (this.loginForm.userPwd === "") {
        this.passwordReadonly = true;
      } else {
        if (this.loginForm.userPwd == this.originPwd) {
          this.loginForm.userPwd = "";
        }
      }
      setTimeout(() => {
        this.passwordReadonly = false;
      }, 0);
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值