问题

今天做项目,登录注册使用了VUE2+elementUI,

但发现其自带的autocomplet=off,还是网上说的的autocomplete="new-password"都不管用,

另外的方法是通过预先设定readonly=true,el-input添加点击事件,当点击时改变readonly=false,

也不好使,但基于这个方法,我优化了一下,

虽然实现的效果确实点击输入框不会跳出浏览器自动填入,但输入的时候,还是会跳出,

不过总而言之是可以用了。

方法

VUE2+elementUI

首先在main.js中注册全局指令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 注册全局指令input-readonly
Vue.directive('input-readonly', {
inserted(el) {
const inputElement = el.querySelector('.el-input__inner');
if (!inputElement) return;

inputElement.readOnly = true;

inputElement.oninput = function(event) {
handleEvent(event);
};

inputElement.onmousedown = function(event) {
handleEvent(event);
};

function handleEvent(event) {
if (event.target.value === '') {
inputElement.readOnly = true;
window.requestAnimationFrame(() => {
inputElement.readOnly = false;
});
}
}
}
})

接着,你就可以在组件里的el-input中把v-input-readonly添加使用即可:

1
2
<el-input ref="email" v-model="loginForm.email" placeholder="请输入电子邮箱" name="email" type="text"
tabindex="3" style="width: 350px" v-input-readonly />

VUE3+elementPlus

同理,首先在main.js中注册全局指令,

只不过

  • 指令注册方式不同:Vue 3使用 app.directive() 而不是 Vue.directive()
  • 生命周期钩子名称变化: inserted 改为 mounted
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 注册全局指令input-readonly
app.directive('input-readonly', {
mounted(el) {
const inputElement = el.querySelector('.el-input__inner');
if (!inputElement) return;

inputElement.readOnly = true;

inputElement.oninput = function(event) {
handleEvent(event);
};

inputElement.onmousedown = function(event) {
handleEvent(event);
};

function handleEvent(event) {
if (event.target.value === '') {
inputElement.readOnly = true;
window.requestAnimationFrame(() => {
inputElement.readOnly = false;
});
}
}
}
})

接着,你就可以在组件里的el-input中把v-input-readonly添加使用即可:

1
2
<el-input ref="email" v-model="loginForm.email" placeholder="请输入电子邮箱" name="email" type="text"
tabindex="3" style="width: 350px" v-input-readonly />