enter键的使用

vue全部的按键别名:

  • .enter
  • .tab
  • .delete (捕获“删除”和“退格”键)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

vue中

<input v-on:keyup.enter="submit">  缩写:<input @keyup.enter="submit">
<input type="text" @keyup.enter="test(1)">

在使用过程中,如果页面只针对一个Input添加键盘enter事件,可以直接按照官方文档定义的别名增加相应事件就可以了

<el-button type="success" @click.enter="watchEnter()">登录</el-button>  无效写法

但是如果是要对页面的button添加enter键盘事件,就不能写在input或者button上,因为获取不到焦点,这时候可以直接写在created里,如下:

写法一

created() {  
    var _this = this;
    document.addEventListener("keydown", _this.watchEnter);
  },  
  destroyed() {
    //移除监听回车按键
    var _this = this;
    document.removeEventListener("keydown", _this.watchEnter);
  },
  methods:{
    //监听回车按钮事件
    watchEnter(e) {
      var keyNum = window.event ? e.keyCode : e.which; //获取被按下的键值
      //判断如果用户按下了回车键(keycody=13)
      if (keyNum == 13) {
        按下回车按钮要做的事
      }
    },
  }

写法二 

       
mounted(){ let _this
= this; document.onkeydown = function(e) { var key = window.event ? e.keyCode : e.which; if (key == 13) { console.log('000') _this.submitForm(_this.formName); } } },

     destroyed() {
        document.onkeydown = null;
    }

 

猜你喜欢

转载自www.cnblogs.com/mary-123/p/12066250.html