[Vuejs]-Change input field focus in JS

0👍

The autofocus attribute

lets you specify that a form control should have input focus when the
page loads

You need something to call focus() on the element that should receive focus. A directive can do that. I used nextTick because otherwise the initial focus didn’t get set right.

var data = {
  whichHasFocus: 'box1'
}

var demo = new Vue({
  el: '#demo',
  data: data,
  methods: {
    changeFocus() {
      this.whichHasFocus = this.whichHasFocus == 'box1' ? 'box2' : 'box1';
    }
  },
  directives: {
    focusIf(el, binding) {
      if (binding.arg === binding.value) {
        Vue.nextTick(() => el.focus());
      }
    }
  }
})
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="demo">

  <input type="text" placeholder="box1" v-focus-if:box1="whichHasFocus"><br>
  <input type="text" placeholder="box2" v-focus-if:box2="whichHasFocus"><br>
  <button @click="changeFocus()">Change Focus</button>

</div>

0👍

You can defined one customized command by directives, then in the handler, focus the element depending on the state of your data binding (below is box1/box2).

You can look into Vue Focus to study further.

var demo = new Vue({
    el: '#demo',
    data: {
      box1: true,
      box2: false
    },
    methods: {
    	changeFocus() {
      	this.box1 = false;
        this.box2 = true;
      }
    },
    directives: {
    focus: {
      update: function (el, {value}) {
        if (value) {
          el.focus()
        }
      }
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<html>
<body>
<div id="demo">

    <input type="text" placeholder="box1" v-focus="box1" @blur="box1 = false"><br>
    <input type="text" placeholder="box2" v-focus="box2" @blur="box2 = false"><br>
    <button @click="changeFocus()">Change Focus</button> 

</div>
</body>
</html>

Leave a comment