vue 实现阻止浏览器记住密码功能
一、密码框的 type 定义为 text
- 把密码框的 type 定义为 text ,这样浏览器就无法正确自动识别密码;
- 给输入框绑定事件 , 每次输入数据触发事件, 把密码替换成圆点 ●;
- 给输入框右侧 小眼睛手动绑定事件 ,控制密码的显示隐藏
<div class="login-location">
<el-input
prefix-icon="el-icon-lock"
v-model="pwdCover"
type="text"
name="pwd"
id="pwd"
placeholder="密码"
autocomplete="off"
@input="setPassword"
@keyup.enter.native="userLogin()"
>
<i
slot="suffix"
class="el-icon-view"
style="margin-top: 10px; margin-right: 10px; font-size: 18px"
@click="hidePassword"
></i>
</el-input>
</div>
// 输入框输入事件
setPassword(val) {
if (this.isShowPassword) {
this.password = val;
} else {
let reg = /[0-9a-zA-Z]/g; // 只允许输入字母和数字
let nDot = /[^●]/g; // 非圆点字符
let index = -1; // 新输入的字符位置
let lastChar = void 0; // 新输入的字符
let realArr = this.password.split(""); // 真实密码数组
let coverArr = val.split(""); // 文本框显示密码数组
let coverLen = val.length; // 文本框字符串长度
let realLen = this.password.length; // 真实密码长度
// 找到新输入的字符及位置
coverArr.forEach((el, idx) => {
if (nDot.test(el)) {
index = idx;
lastChar = el;
}
});
// 判断输入的字符是否符合规范,不符合的话去掉该字符
if (lastChar && !reg.test(lastChar)) {
coverArr.splice(index, 1);
this.pwdCover = coverArr.join("");
return;
}
if (realLen < coverLen) {
// 新增字符
realArr.splice(index, 0, lastChar);
} else if (coverLen <= realLen && index !== -1) {
// 替换字符(选取一个或多个字符直接替换)
realArr.splice(index, realLen - (coverLen - 1), lastChar);
} else {
// 删除字符,因为 val 全是 ● ,没有办法匹配,不知道是从末尾还是中间删除的字符,删除了几个,不好对 password 处理,所以可以通过光标的位置和 val 的长度来判断
let pos = document.getElementById("pwd").selectionEnd; // 获取光标位置
realArr.splice(pos, realLen - coverLen);
}
// 将 pwdCover 替换成 ●
this.pwdCover = val.replace(/\S/g, "●");
this.password = realArr.join("");
}
},
// 点击右侧小眼睛控制显示隐藏
hidePassword() {
if (!this.isShowPassword) {
// console.log("显示");
this.isShowPassword = true;
this.pwdCover = this.password;
} else {
// console.log("隐藏");
this.isShowPassword = false;
this.pwdCover = this.pwdCover.replace(/\S/g, "●");
}
},
// 登录的逻辑
userLogin() {
if (this.account === "admin" && this.password === "admin") {
this.loading = true;
setTimeout(() => {
this.$router.push({ path: "/main" });
}, 600);
this.$message.success("登录成功");
}
}
参考文章链接:https://www.jb51.net/javascript/288844opq.htm