前言
想要设置浏览器不记住密码,改变input的type为text,通过css样式-webkit-text-security: disc;实现。但是这个属性只适用于谷歌浏览器
以下步骤通过js实现该功能
一、html 首先设置input的type
<el-form-item prop="password" label="原密码:">
<el-input v-model="password1" type="text" placeholder="请输入原密码" autocomplete="off" class="password-input" @input="changeInput('password')">
</el-input>
</el-form-item>
<el-form-item prop="newPassword" label="新密码:">
<el-input v-model="newPassword1" type="text" @input="changeInput('newPassword')" placeholder="6-12位的字母、数字、特殊符号至少2种组成的密码" autocomplete="off" class="password-input">
</el-input>
</el-form-item>
二、js
1.变量定义
每个密码框对应两个变量,一个用于接收用户的输入内容(转换为.用作展示),另一个用于表单校验和接口提交(真正的密码内容)
const formMsg = reactive({
formData: {
password: '',
password1: '',
newPassword: '',
newPassword1: '',
rePassword: '',
rePassword1: ''
}
})
2.用户输入内容时触发input事件,绑定方法changeInput
参数用于区分是那个input的值发生了变化。
const changeInput = (name) => {
const event = window.event || arguments.callee.caller.arguments[0]
let data = event.data
let end = event.target.selectionEnd
let newPassword = formMsg.formData[name + '1']
let password = formMsg.formData[name]
if (/[\u2000-\u206f\u3000-\u303f\u4e00-\u9fef\uff00-\uffef]|(^\s+)|(\s+$)/.test(data)) {
const deleteNum = data.length
const start = end - data.length
newPassword = newPassword.split('')
newPassword.splice(start, deleteNum)
formMsg.formData[name + '1'] = newPassword.length > 0 ? newPassword.join('') : ''
password = password.split('')
password.splice(start, password.length - newPassword.length)
formMsg.formData[name] = newPassword.length > 0 ? password.join('') : ''
} else {
if (password.length === 0) {
formMsg.formData[name] = data
} else {
const deleteNum = data === null ? password.length - newPassword.length : password.length - newPassword.length + 1
const start = data === null ? end : end - data.length
password = password.split('')
password.splice(start, deleteNum, data)
formMsg.formData[name] = password.join('')
}
formMsg.formData[name + '1'] = ''
for (let index = 0; index < newPassword.length; index++) {
formMsg.formData[name + '1'] += '.'
}
}
console.log(formMsg.formData[name], formMsg.formData[name + '1'])
}
3:防止粘贴
onMounted(() => {
document.addEventListener('paste', function (e) {
if (e.target.offsetParent.classList.contains('password-input')) {
e.preventDefault()
}
})
})