Vue - execute method on blur when no input focused

Viewed 204

I'm trying to find a way to prevent method execution when any of 2 inputs have focus.

Both inputs should fire method on blur and prevent it when focused. Using single of these inputs works good.

The problematic situation is when blurring from input_1 and immediately focusing on input_2 (e.g. using tab) - it fires the method before input_2 gets focus.

What I would like to achieve is preventing the method execution in this case.

What I already tried:

  • using flags as presented in example code -> failed as described,
  • getting activeElement in fired method -> instead of getting input element, I'm getting main vue app <div id="app" />

Example code:

<template>
  <div>
    <input id="input_1" @blur="changeFlagAndExecuteMethod()" @focus="focused = true"></input>
    <input id="input_2" @blur="changeFlagAndExecuteMethod()" @focus="focused = true"></input>
  </div>
</template>

<script>
export default {
  data () {
    return {
      focused: false
    }
  },
  methods: {
    changeFlagAndExecuteMethod () {
      this.focused = false
      this.doSomething()
    },
    doSomething () {
      // document.activeElement => results with main <div id="app" /> instead of input

      if (this.focused) return
      // otherwise execute method
    }
  }
}
</script>
1 Answers

One solution is to execute doSomething() in the next macro tick, using setTimeout() with a zero delay (ms is 0 by default), at which point the second input will have received focus, and its focus handler will already have been invoked:

changeFlagAndExecuteMethod () {
  this.focused = false
  setTimeout(() => this.doSomething()) // execute in next macro tick
} 

demo

Related