13

When span class="before-click" is clicked,
I want it hidden, and input class="after-click" show up instead.
And the showed up input tag must be on focused!
The problem is when I try to use $refs.afterClick to access that DOM and give it .focus(), an unexpected error shows that .focus() is not a function.
How to solve this issue? Thanks.

var myApp = new Vue({
  el: '#app',
  data: {
    onEdit: false,
    msg: 'Something in here',
  },
  methods: {
    switchAndFocus() {
      if(!this.onEdit) {
       this.onEdit = true;
       this.$refs.afterClick.focus();
      }
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <span class="before-click" @click="switchAndFocus()" v-show="!onEdit">{{msg}}</span>
  <input type="text" class="after-click" ref="afterClick" :value="msg" v-show="onEdit">
</div>
Arel Lin
  • 908
  • 2
  • 13
  • 24

1 Answers1

34

Wrap the focus event in a nextTick - this will defer the focus event until the DOM has updated and displayed the input.

https://v2.vuejs.org/v2/api/#Vue-nextTick

var myApp = new Vue({
  el: '#app',
  data: {
    onEdit: false,
    msg: 'Something in here',
  },
  methods: {
    switchAndFocus() {
      if(!this.onEdit) {
       this.onEdit = true;
       this.$nextTick(function(){
        this.$refs.afterClick.focus();
       });
      }
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <span class="before-click" @click="switchAndFocus()" v-show="!onEdit">{{msg}}</span>
  <input type="text" class="after-click" ref="afterClick" :value="msg" v-show="onEdit">
</div>
tony19
  • 125,647
  • 18
  • 229
  • 307
tom_h
  • 876
  • 2
  • 9
  • 15
  • 1
    Thanks! This is exactly what I need, but why focus event happens faster than DOM? – Arel Lin Nov 21 '17 at 11:26
  • 3
    You were calling .focus() on an element that didn't yet exist. So you must wait for the DOM to update and create the element. This is to do with the lifecycle hooks in Vue. Often if you are having issues with data or rendering it is because of a misunderstanding of the lifecycle: https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram – tom_h Nov 21 '17 at 15:35
  • Wow... that was a bunch of stuff, I'll try to understand it. Thanks! – Arel Lin Nov 22 '17 at 02:43