Detailed explanation of binding keyboard events in vue project

In the Vue project, sometimes it is encountered that a keyboard event is bound to a text input box or a button button, and the most common one is the enter event.

According to the method given by the vue official website:

v-on:keyup.enter

Shorthand:

@keyup.enter

If it is bound to the component, you need to add the native modifier

 <el-input
          v-focus
          :placeholder="$t('enterPoolName')"
          v-model.trim="strPool"
          :maxlength="100"
          @keyup.enter.native="handleSearchMember"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>

However, this method can only work when the focus is obtained. If the focus is lost, keyboard events cannot be performed.

If the project needs to lose focus, it can still execute the corresponding keyboard event and complete the predetermined behavior, such as submitting the form to log in and so on.

Then you need to take a conventional method, bind the keyboard event to the document document, and then execute the keyboard event response by obtaining the value of each key on the keyboard.

mounted() {
    const that = this;
    document.addEventListener('keydown', that.handleWatchEnter);
  },
  methods: {
    handleWatchEnter(e) {
      var key = window.event ? e.keyCode : e.which;
      console.log(key);
      if (key === 13) {
        // 这里执行相应的行为动作
        console.log('++++');
      }
    },
}

Finally, attach the value corresponding to each key on the keyboard, and the writing method of the vue keyboard event:

Button keyboard event in vue 

@keydown (triggered when the keyboard is pressed), @keypress (triggered when the keyboard is pressed), @keyup (keyboard popped up)

Get the key code e.keyCode of the key

@keyup.13 press enter

@keyup.enter Enter

@keyup.up key up

@keyup.down down key

@keyup.left left button

@keyup.right right

@keyup.delete delete key

Guess you like

Origin blog.csdn.net/sinat_36728518/article/details/114932587#comments_27492304