简体   繁体   中英

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].

<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. This means that the condition in listenToKeyup is being determined, however keyup.enter is not being fired. 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.

Can someone kindly show me what I'm doing wrong, please?

The problem is the 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:

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

Codesandbox example

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