简体   繁体   中英

Is it possible to target an input element using @keyup inside a custom component?

Hi I wanted to target an input element inside a custom component using v-on:keyup, but apparently I have no luck

 <TextField label="Some Text" @keyup="updateLen" v-model="text"  />

//javascript
computed: {
updatedLen(event) {
  let target = event.value.length;

  console.log('target', target)
},
}

here is the custom component src code

<template>
<div>
<v-text-field>@keyup="keyUp"</v-text-field>
</div>
</template>

<script>
keyUp(event)
    {
      
      this.content =   this.content.replace(/([^a-z0-9-]+)/gi, '');
        

      this.$emit('input', this.content);
     
    },
</script>

On custom components, listeners like @myEvent will listen to custom events emitted with this.$emit . So here, @keyup is listening to custom events this.$emit('keyup') ( It's not the native keyup event from the DOM. )

Here, your TextField component never emit a keyup event, so your listener won't ever be triggered. Even if you have a component inside that triggers an event with the same name, this event isn't dispatch to the parents, only to its direct parent (ie the component using it).

What you have to do it emitting the event again while listening to it.

<TextField label="Some Text" @keyup="updateLen" v-model="text"  />
<template>
  <div>
    <v-text-field @keyup="keyUp"></v-text-field>
  </div>
</template>

<script>
  keyUp(event) {
     this.content = this.content.replace(/([^a-z0-9-]+)/gi, '');
     this.$emit('input', this.content); // Updates `v-model`
     this.$emit('keyup', event); // Triggers your `@keyup` listener
  },
</script>

If your TextField component is only a wrapper to v-text-field and you expect it to have the exact same props / listeners, you can disable to auto inheritance of attributes and set it yourself.

<template>
  <div>
    <v-text-field v-on="$listeners" v-bind="$attrs">
  </div>
</template>

<script>
export default {
   inheritAttrs: false, // The root element won't inherit all static attrs
}
</script>

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