欢迎各位看官大佬光临,麻烦各位文章末尾一键三联,你的支持是我坚持下去的动力,谢谢!!!
在项目中我们想要实现点击按钮或者直接点击键盘回车键实现一键登录该怎么做呢?
我们可以给登录按钮绑定两个点击事件:(代码如下)
<el-button type="primary" @click="login" @keyup.enter="login">登录</el-button>
login 是直接点击按钮的登录事件
methods: {
login() {
console.log("ok");
this.$refs.loginFormRef.validate(async (valid) => {
if (!valid) return;
try {
const { data: res } = await this.$http.post(
"/admin/login",
this.loginForm
);
// console.log(res)
if (res.status !== 200) return this.$message.error("登录失败!");
// this.$message.success('登录成功')
this.$message({
offset: 60,
message: "登录成功",
type: "success",
duration: 600,
});
// 将登录成功之后的 token,保存到客户端的 sessionStorage 中
window.sessionStorage.setItem("token", res.data.token);
window.localStorage.setItem(
"user_name",
this.loginForm.sysUserAccount
);
this.$router.push("/situation");
} catch (error) {
// this.$message.error(error);
}
});
// this.$router.push("/situation");
},
// 点击回车键登录
keyDown(e) {
// 回车则执行登录方法 enter键的ASCII是13
if (e.keyCode === 13) {
this.login(); // 定义的登录方法
}
},
},
mounted() {
// 绑定监听事件
window.addEventListener("keydown", this.keyDown);
},
destroyed() {
// 销毁事件
window.removeEventListener("keydown", this.keyDown, false);
},
这样就可以实现点击键盘回车键和点击按钮实现登录功能!!!