vue中监听键盘输入的两种方法

765 阅读1分钟

在一个简单的项目中,需要对小键盘的+ - * / .五个按键进行监听,完成一定的操作。具体有两个较为简单的实现方法,方法一通过在created()函数中对键盘输入进行相应(需要查询键盘键值),方法二通过监听输入框的输入值实现。

方法一

created() {
    var _this = this;
    document.onkeydown = function (e) {
      if (_this.$router.currentRoute.value.name == "check") {
        let key = window.event.keyCode;
        _this.barcodefocus();
        if (_this.dialogVisible == false) {
          if (key == 107) {
            _this.value = "A";
            _this.tyreid = "";
            return;
          } else if (key == 109) {
            _this.value = "B";
            _this.tyreid = "";
            return;
          } else if (key == 106) {
            _this.value = "C";
            _this.tyreid = "";
            return;
          } else if (key == 111) {
            _this.value = "D";
            _this.tyreid = "";
            return;
          } else if (key == 110) {
            _this.value = "F";
            _this.tyreid = "";
            return;
        } else 
        if (_this.dialogVisible == false) {
          if (key == 13 || key == 108) {
            //回车 大小都要
            //_this.barcodefocus();
            _this.dualfunc();
            //_this.barcodefocus();
          } else {
            _this.barcodefocus();
          }
        } else {
          _this.passfocus();
        }
      }

在这种方法中,需要注意的是,小键盘数字按键键值与大键盘不同(回车也不相同)为107对应小键盘+,109对应小键盘-,106对应小键盘*,111对应小键盘/,110对应小键盘.。

具体键值参考:键盘按键的键码值(全) - 空城机 - 博客园 (cnblogs.com)

方法二

方法二是通过对输入框中所输入的值进行监听,也就是必须要有输入框才能实现(方法一可以不用)

watch: {
    tyreid(tyreid) {
      console.log(tyreid)
      if (
        tyreid == "+"
      ) {
        this.value = "A";
        this.tyreid = "";
      } else if (tyreid == "-") {
        this.value = "B";
        this.tyreid = "";
      } else if (tyreid == "*") {
        this.value = "C";
        this.tyreid = "";
      } else if (tyreid == "/") {
        this.value = "D";
        this.tyreid = "";
      } else if (tyreid == ".") {
        this.value = "F";
        this.tyreid = "";
      }
    },
  },

检测到输入的对应字符,执行对应操作并清空输入框,完成操作。

总结

在选用方法一时,如焦点在输入框上,输入框上会留有字符(也可以通过方法二的watch进行监听取消,这样就不如直接用方法二了哈哈)。在使用这两种方法进行实现后,由于业务只有一个输入框,且为了影响输入,最终选择了方法二。