1

I have some autocomplete thingy in vuejs. When you start typing you get a list and if you click on some element that has some function bind to it, that function is never executed because of blur. But keep in mind that someone maybe clicked outside without selecting anything (list should be closed).

I have made jsfiddle with example: https://jsfiddle.net/4m47bbh3/1/

new Vue({
  el: "#app",
  data:{
    open: false,
    letter: ""

  },
  methods: {
    set_data(letter) {
        this.letter = letter
    },
    _close(){
        this.open = false;
      //i can add here setTimeOut function but i dont know how many  miliseconds/seconds blur will be pressed
      //someone can hold it for 10 - 20 just to proof that you cna not relay on setTimeout
    },
    _show(){
        this.open = true;
    }
  }
})
<div id="app">
  <input v-on:blur="_close" v-on:keyup="_show"/>
  <ul v-if="open">
    <li v-on:click="set_data('A')">A</li>
    <li v-on:click="set_data('B')">B</li>
    <li v-on:click="set_data('C')">C</li>
  </ul>
  <div>
  {{letter}} 
  <!-- this letter will be always empty -->
  </div>
</div>

As i commented in example i can do setTimeOut but that will just not work since i dont know for how many miliseconds/seconds blur will last.

pregmatch
  • 2,629
  • 6
  • 31
  • 68
  • What are you trying to do? Finding how much time user is not having focus in input field? And why do you need it? – sabithpocker May 17 '18 at 10:05
  • well i am looking to slove that blur issue and as far as i can see only way is to know how many milliseconds blur (not focus) took – pregmatch May 17 '18 at 10:06
  • if you look at jsfiddle you will se what is happening when you blur – pregmatch May 17 '18 at 10:07
  • One workaround would be to call _close in the set_data methods after setting this.letter instead of calling it on the blur event. – Oli Crt May 17 '18 at 10:19

1 Answers1

3

blur is triggered before click. That's why the click event listener is never triggered.

Here's an explanation from https://stackoverflow.com/a/10653160/5599288

Listen to mousedown instead of click.

The mousedown and blur events occur one after another when you press the mouse button, but click only occurs when you release it.

demo: https://jsfiddle.net/4m47bbh3/2/

change it to mousedown and it works

 <ul v-show="open">
    <li v-on:mousedown="set_data('A')">A</li>
    <li v-on:mousedown="set_data('B')">B</li>
    <li v-on:mousedown="set_data('C')">C</li>
  </ul>
Jacob Goh
  • 19,800
  • 5
  • 53
  • 73