user2950593
user2950593

Reputation: 9637

Vue js stop second event

I have input with some info.

On blur event or on enter press I want to do some action But when I press enter my input loses focus and two events are fired one after another-what do I do?

<input  v-on:keyup.13.prevent ='save_renamed_group(g)'
                    @blur.prevent = 'save_renamed_group(g)'>

UPD: I don't consider my question as duplicate of this one: Prevent both blur and keyup events to fire after pressing enter in a textbox

simply because I want a clear and clean and nice solution to this simple and common stuff and all solutions posted there look like a little bit of hell.

Upvotes: 1

Views: 2355

Answers (1)

Jacob Goh
Jacob Goh

Reputation: 20845

Solution 1: apply debounce on the method.

Debouncing essentially groups your events together and keeps them from being fired too often. To use it in a Vue component, just wrap the function you want to call in lodash’s _.debounce function.

https://alligator.io/vuejs/lodash-throttle-debounce/

import { debounce } from 'lodash';

export default {
  methods: {
    // group all function calls within 100ms together
    // no matter how many times this function is called within 100ms, only 1 of them will be executed.
    save_renamed_group: debounce(g => {
      // ...
    }, 100),
  },
};

Pros: simple

Cons: delayed function execution


Solution 2: store state of function execution in a variable

export default {
  created() {
    // create the variable
    this.save_renamed_group_running = false;
  },
  methods: {
    save_renamed_group(g) {
      // exit if function is already running
      if (this.save_renamed_group_running) return;

      // set running to true
      this.save_renamed_group_running = true;

      // .... other logic ...

      // set running to false before exiting
      this.save_renamed_group_running = false;
      return /* something */;
    },
  },
};

Pros: immediate function execution

Cons: verbose

Upvotes: 2

Related Questions