Home  >  Article  >  Web Front-end  >  vue.js listens to keyboard events

vue.js listens to keyboard events

angryTom
angryTomOriginal
2019-07-16 15:49:083705browse

Vue monitors the keyboard, just bind it with @, and Vue provides aliases for several commonly used keys, so you don’t need to query the keyCode

all Key alias

.enter

# .space

.up

.down

.left

.right

1. The input tag binds the esc key

and binds the event in

<input type="text" @keyup.esc="KeyUpEsc">
<script></script>
KeyUpEsc:function(){
      alert("监听到esc键")
  }

Function rendering


2. Use the el-input tag of the element component library and bind the delete key

vue.js listens to keyboard events

Binding event in

<el-input v-model="input" placeholder="请输入内容" @keyup.delete.native="KeyUpDelete"></el-input>
Why does the binding event have an extra .native modifier this time? This may be because element-ui encapsulates a div Outside the input tag, the original event is hidden, so if .native is not added, the keystroke will not take effect

<script></script>Events defined in

 KeyUpDelete :function(){
      alert("监听到delete键")
  },

3. The above two implementation effects are that the keyboard can be monitored only when the input tag gets the focus. The following one is to globally monitor the enter key and bind the monitoring event to the document. (Commonly used on login pages)

vue.js listens to keyboard events

 created: function() {
        var _this = this;
        document.onkeydown = function(e) {
            let key = window.event.keyCode;
            if (key == 13) {
                _this.submit();
            }
        };
    },
   methods: {
        submit: function() {
            alert("监听到enter键");
        },
   }

The rendering is shown in the picture

##For more js related knowledge, you can click me:

js tutorial

vue.js listens to keyboard events

The above is the detailed content of vue.js listens to keyboard events. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn