<template>
<div>
<button id="btn_login" @click="handleLogin">Login</button>
</div>
</template>
<script>
export default {
mounted() {
// 在 Vue 组件加载完成后绑定 keyup 事件
document.body.addEventListener('keyup', this.handleKeyup);
},
beforeDestroy() {
// 在组件销毁前移除事件监听
document.body.removeEventListener('keyup', this.handleKeyup);
},
methods: {
handleLogin() {
// 处理登录逻辑
alert('Login clicked!');
},
handleKeyup(e) {
// 检测回车键 (keyCode 13)
if (e.keyCode === 13) {
// 模拟点击登录按钮
this.handleLogin();
}
}
}
};
</script>
在 Vue 中绑定回车键事件
于 2025-05-14 15:13:29 首次发布