0

I have a custom component which is basically an input with some styles. I want to alert something when the user focuses out of the component. I added @blur and tabindex but it still doesn't alert anything. what's wrong with my code here? the custom component doesn't emit anything on blur though

<template>
  <custom-component v-model="email" @blur="showSomething" tabindex="0"/>
</template>

<script>
export default{
 data(){
  return{
    email
  };
 },
 methods{
  showSomething(){
    alert('yes')
 }
</script>
1

1 Answer 1

2

Since it's a custom component, you need to manually specify events that it should emit, using Vue's $emit() instance method.

I don't know what your underlying component code looks like, but it can be as simple as adding $emit('blur', $event) to your input's blur handler:

<input v-model="xxx" ... @blur="$emit('blur', $event)">

($event is just special Vue syntax for referencing the original DOM event in an inline statement handler. You can omit it if you don't need access to it– just call $emit with only the first argument: $emit('blur').)

If you already have a handler/ method being called on the blur event in that component, then you can alternatively add $emit into that method, just don't forget the this:

methods: {
  ...
  blurHandler() {
    ...
    this.$emit('blur');
    ...
  },
  ...
},

There are other solutions to this, but explicitly calling vm.$emit() is probably the most straightforward and clear.

6
  • it's a component from a library. i can't make any change to the component Commented May 24, 2021 at 19:07
  • @allhopelost You should give this solution a look this, it uses Vue's .native event modifier.
    – zcoop98
    Commented May 24, 2021 at 19:11
  • done that. didn't work. most probably because there's a label element too in the custom component, not just input.. Commented May 24, 2021 at 19:36
  • Your last resort is probably $listeners then, as described in this answer, and further down under .native in the docs. You might also double check that the library itself doesn't provide any way to get a blur event or provide some equivalent too; that's a very standard event, it's pretty strange that they left it out altogether.
    – zcoop98
    Commented May 24, 2021 at 19:42
  • @allhopelost You can only listen to events that the component emits. If the component does not emit a blur event, using @blur will not have any effect. What component library are you using?
    – tony19
    Commented May 24, 2021 at 22:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.