created() {
let that = this;
document.onkeypress = function(e) {
var keycode = document.all ? event.keyCode : e.which;
if (keycode == 13) {
that.login();// 登录方法名

return false;
}
};
}
created() {
let that = this;
document.onkeypress = function(e) {
var keycode = document.all ? event.keyCode : e.which;
if (keycode == 13) {
that.login();// 登录方法名

return false;
}
};
}以上的代码,在这几天测试发现有一个问题,在登录进系统之后,从首页切换到其他界面,点击回车,会导致界面调整到首页!要实现:要实现:只在Login界面点击回车才执行onkeypress方法,其他的点回车均不触发(还不明白为什么在其他界面回车会执行Login界面的created-_-|| )思路:思路:在Login.vue最外层绑定id,再绑定键盘事件。$(“#loginDiv”).bind("keypress",toLogin);$(“#loginDiv”).bind("keypress",toLogin);测试发现监听不到按键事件,因为div元素没法获取焦点,但只要为div元素加上tabIndex属性就能获取焦点
以上方法虽然也能触发keypress,但还有点瑕疵~ 就是打开登录页时,需要鼠标点一下界面,才能触发keypress!!!又一思路:界面中需要有一个聚焦,在回车时才好执行keypress。故在界面中加input文本框,让不管从哪里打开或跳到Login.vue都聚焦文本框所以自定义指令:






directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus()
}
}
},
directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus()
}
}
},自定义指令及inserted用法截图自vue官网文档如下:知识点补充:知识点补充:知识点补充:vue项目里登录界面实现回车登录vue项目里登录界面实现回车登录vue项目里登录界面实现回车登录方法一:在vue的created钩子函数中写
//登录添加键盘事件,注意,不能直接在焦点事件上添加回车
// let that = this;
// document.onkeydown = function (e) {
//
e = window.event || e;
// if(that.$route.path=='/login'&&(e.code=='Enter'||e.code=='Num Enter')){//验证在登录界面和按得键是回车键enter
//
that.handleSubmit2('ruleForm2');//登录函数 (handleSubmit2('ruleForm2')-登录按钮的点击事件)
// }
// }
//登录添加键盘事件,注意,不能直接在焦点事件上添加回车
// let that = this;
// document.onkeydown = function (e) {
//
e = window.event || e;
// if(that.$route.path=='/login'&&(e.code=='Enter'||e.code=='Num Enter')){//验证在登录界面和按得键是回车键enter
//
that.handleSubmit2('ruleForm2');//登录函数 (handleSubmit2('ruleForm2')-登录按钮的点击事件)
// }
// }注意:只对主键盘的Enter管用方法二:在vue的created钩子函数中写
var _self = this;

document.onkeydown = function(e){

var key = window.event.keyCode;

if(key == 13 || key == 100){

_self.handleSubmit2('ruleForm2');

}
}
var _self = this;

document.onkeydown = function(e){

var key = window.event.keyCode;

if(key == 13 || key == 100){

_self.handleSubmit2('ruleForm2');

}
}对主键盘和小键盘的Enter都管用总结总结总结以上所述是小编给大家介绍的vue中实现回车键登录功能,希望对大家有所帮助,也非常感谢大家对网站的支持!