简体   繁体   English

如何添加事件侦听器以记录 vue 中的更改?

[英]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?但是如何在 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.如果您的文档根目录上有另一个 Vue 实例,您可以使用自定义事件。

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 ):如果您的body元素上没有实例,您可以在创建 Vue 实例时在文档上创建一个事件侦听器(示例):

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

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

Try this尝试这个

html html

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

js js

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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