简体   繁体   中英

How do I add event listener to document changes in vue?

I can add a watch property to a input form. But what if user presses a key. I want print the key press when the user is on the page.

$(document).keypress(function(event){
            alert(String.fromCharCode(event.which));
        });

But how do I add the check for keypresses in vue?

You have two options for registering the global event listener.


If you have another Vue Instance on your document's root you could use custom events.

Add to your main instance:

<body @keydown="this.$emit('onkeydown')">...</body>

And to your nested instance:

<my-component v-on:onkeydown="alert(String.fromCharCode(event.which));"></my-component>

This emits a global event which is caught by your nested instance. If you want to know more about custom events click here .


If there is no instance on your body element you can just create an event listener on the document when your Vue instance is created ( Example ):

  methods: {
    onkeydown(e) {
      alert(String.fromCharCode(event.which));
    }
  },

  created() {
    document.onkeydown = this.onkeydown;
  }

Try this

html

<div id="test">
  <input v-on:keyup="say()">Say hi</input>
</div>

js

new Vue({
  el: '#test',
  methods: {
    say: function (e) {
      alert(e.keyCode)
    }
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM