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

vue.js listens to keyboard events

angryTom
Release: 2019-07-17 08:41:40
Original
3809 people have browsed it

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">
Copy after login
<script></script>
KeyUpEsc:function(){
      alert("监听到esc键")
  }
Copy after login

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>
Copy after login
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键")
  },
Copy after login

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();
            }
        };
    },
Copy after login
   methods: {
        submit: function() {
            alert("监听到enter键");
        },
   }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template