vue使用快捷键(F1-F12),聚焦el-input框并选中文本

业务需求:通过键盘快捷键,如:F2,选中input框,可直接输入值。

  • 页面input

 
 
  • 事件监听和触发input聚焦

 data(){
      return{
          focusState: false
      }
  },
  mounted(){
      addEventListener('keydown', this.keyDown)//创建监听键盘事件
  },
  directives: {
    focus: {
      //根据focusState的状态改变是否聚焦focus
      update: function (el, { value }) {    //第二个参数传进来的是个json
        if (value) {
          //使用的el-input
          el.getElementsByTagName("input")[0].focus()
        }
      }
    }
  },
  method:{
  //得到焦点选中
    focusSelect (event) {
      event.currentTarget.select();
    },
   keyDown(e) {
      console.log(e);
      if (e.key == 'F2') {
        this.focusState= true
        e.preventDefault();//阻止浏览器默认事件
        return false
      }
    },
  }

你可能感兴趣的:(vue使用快捷键(F1-F12),聚焦el-input框并选中文本)