Vue監(jiān)聽鍵盤,直接用@綁定就可以,而且Vue為幾個常用的按鍵提供了別名,不用去查詢按鍵的keyCode
- 全部的按鍵別名
.enter
.tab
.delete (捕獲“刪除”和“退格”鍵)
.esc
.space
.up
.down
.left
.right
一、input標簽綁定esc鍵
-
<template></template> 中綁定事件
<input type="text" @keyup.esc="KeyUpEsc"> -
<script></script>中定義事件
KeyUpEsc:function(){ alert("監(jiān)聽到esc鍵") }

實現(xiàn)效果截圖
二、使用element組件庫的el-input標簽,綁定delete鍵
- <template></template> 中綁定事件
<el-input v-model="input" placeholder="請輸入內(nèi)容" @keyup.delete.native="KeyUpDelete"></el-input>
為什么這次綁定事件多一個.native修飾符,這個可能是因為element-ui封裝了個div在input標簽外面,把原來的事件隱藏了,所以如果不加.native的話,按鍵不會生效
-
<script></script>中定義事件
KeyUpDelete :function(){ alert("監(jiān)聽到delete鍵") },

實現(xiàn)效果截圖
三、上面兩種實現(xiàn)效果是當input標簽獲取到焦點的時候,才能監(jiān)聽到鍵盤,下面這種是全局監(jiān)聽enter鍵,是把監(jiān)聽事件綁定到document上(登錄頁面常用)
created: function() {
var _this = this;
document.onkeydown = function(e) {
let key = window.event.keyCode;
if (key == 13) {
_this.submit();
}
};
},
methods: {
submit: function() {
alert("監(jiān)聽到enter鍵");
},
}

實現(xiàn)效果截圖
這里卿洋
愿喜??