在实际应用中,很多时候我们需要监听键盘事件,在vue项目中该如何监听呢?
- 在mounted中新增监听事件
mounted() {
this.dom = document.getElementById("dialogHTTP");
// 监听键盘抬起事件
this.dom.addEventListener("keyup", this.keyPressHandler);
}
- 在methods中写监听事件
keyPressHandler: function (event) {
const key = event.key || String.fromCharCode(event.keyCode);
console.log("key", key);
if (key === "/") {
this.showSystemDownload = true;
// 执行删除操作
} else {
this.showSystemDownload = false;
}
},
- 在beforeDestroy中移除监听事件
beforeDestroy() {
this.dom.removeEventListener("keyup", this.keyPressHandler);
},