Search code examples
vue.jsonfocus

Vue.JS value tied on input having the focus


Is there a way to change a value in the model when an input gets/loses focus?

The use case here is a search input that shows results as you type, these should only show when the focus is on the search box.

Here's what I have so far:

<input type="search" v-model="query">
<div class="results-as-you-type" v-if="magic_flag"> ... </div>

And then,

new Vue({
  el: '#search_wrapper',
  data: {
    query: '',
    magic_flag: false
  }
});

The idea here is that magic_flag should turn to true when the search box has focus. I could do this manually (using jQuery, for example), but I want a pure Vue.JS solution.


Solution

  • Apparently, this is as simple as doing a bit of code on event handlers.

    <input 
      type="search" 
      v-model="query"
      @focus="magic_flag = true"
      @blur="magic_flag = false"
    />
    <div class="results-as-you-type" v-if="magic_flag"> ... </div>