简体   繁体   English

组件父级上的键修饰符

[英]Key modifier on parent of component

Is there a way to record a tab event of a component without having access to the child component? 有没有办法在不访问子组件的情况下记录组件的tab事件?

for example: 例如:

in the Parent: 在家长中:

<inputcomponent
    label="mylabel"
    placeholder="myplaceholder "
    v-on:keydown.tab="keydown($event)"    <---
    >
</inputcomponent>

I have downloaded an autocomplete component from a library so I would like to find a way to record the "tab" event without changing the component, but the parent. 我已从库中下载了自动完成组件,因此我想找到一种方法来记录“ tab”事件,而无需更改组件,而是更改父组件。

Is it possible? 可能吗?

It depends on the component. 这取决于组件。 if the component is not set up to emit listeners, you won't be able to listen to the events this way. 如果未将组件设置为发出侦听器,则您将无法以这种方式侦听事件。

If you cannot edit the component itself, you can go around it by adding custom event listeners during mount (and clearing them on remove) 如果您不能编辑组件本身,则可以通过在挂载期间添加自定义事件侦听器来解决它(并在删除时将其清除)

here is an example that assumes: - you have a component with a ref="componentA" in template - you have a function called onTab - you clear the listener using appropriate event lifecycle 这是一个假设的示例:-您的模板中有一个带有ref="componentA" -您有一个名为onTab的函数-您使用适当的事件生命周期清除了侦听器

  mounted () {
    window.addEventListener('keydown', (e) => {
      if (e.key === 'Tab'){
        var el = e.target;
        while (el) {
          if (el === this.$refs.componentA) {
            // do my action
            return this.onTab();
          }
          el = el.parentElement
        }
      }
    })
  }

This will add an event listener at window level, which will listen to the tab key pressed on ANYTHING . 这将在window级别添加一个事件侦听window ,该侦听window将侦听ANYTHING上按下的tab键。 However, the target element is recursively compared to your current element. 但是,将目标元素与当前元素进行递归比较。 This is not ideal, obviously, since using $emit has lower overhead than looping through any element's parents, which is why clearing this listener is important. 显然,这是不理想的,因为使用$emit开销要比遍历任何元素的父级低,这就是为什么清除此侦听器很重要的原因。

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

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