简体   繁体   English

Vue JS - 有条件的 keyup.enter 不起作用

[英]Vue JS - Conditional keyup.enter is not working

I'm trying to implement a conditional keyup event, however keyup.enter doesn't get fired when I implement it conditionally using a computed property for @[listenToKeyup].我正在尝试实现一个有条件的 keyup 事件,但是当我使用 @[listenToKeyup] 的计算属性有条件地实现它时,keyup.enter 不会被触发。

<template>
   <div>
      <input @[listenToKeyup]="manageSearch"
             v-model="input"
             class="form-input"/>
   </div>
</template>
export default {
    props: {
      skipSearch: {
        type: Boolean,
        required: false,
        default: false
      },
      callback: {
        required: false
      },
    },
  setup(props, {emit}) {
      const input = ref('');

      const listenToKeyup = computed(() => props.skipSearch ? 'keyup.enter' : 'keyup');

      function manageSearch() {
        clearTimeout(searchTimeout)
        searchTimeout = setTimeout(props.callback(input.value), debounce);
      }

  return {
      input,
      listenToKeyup,
      manageSearch,
  };

  }

In this example, props.skipSearch is registered as true in another component and in fact 'manageSearch' does not get fired, whereas in other components where its false, it is fired.在此示例中,props.skipSearch 在另一个组件中注册为 true,实际上“manageSearch”不会被触发,而在其他组件为 false 时,它​​会被触发。 This means that the condition in listenToKeyup is being determined, however keyup.enter is not being fired.这意味着listenToKeyup 中的条件正在确定,但是keyup.enter 没有被触发。 If I try to add the event without the condition '@keyup.enter="manageSearch"', it works as it should, so there isn't an issue with that either.如果我尝试在没有条件'@keyup.enter="manageSearch"' 的情况下添加事件,它会正常工作,所以也没有问题。

Can someone kindly show me what I'm doing wrong, please?有人可以告诉我我做错了什么吗?

The problem is the event-modifier .问题是event-modifier

Dynamic events are possible but modifiers are not supported.动态事件是可能的,但不支持修饰符。

You would have to change your logic to what @Boussadjra Brahim was almost suggesting just with the difference that the modifier has to be written manually:您将不得不将您的逻辑更改为@Boussadjra Brahim 几乎建议的内容,不同之处在于必须手动编写修饰符:

//manage Search
function manageSearch(event) {
  if (!props.skipSearch|| ["Enter"].includes(event.key)) {
    //do your thing
  }
}

Codesandbox example 代码沙盒示例

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

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