Takeshi Tokugawa YD
Takeshi Tokugawa YD

Reputation: 915

Put focus on input field after it will be conditionally rendered in Vue

Target

On click to "edit" button, input field appears and automatically focused.

<button v-if="!editingMode" @click="editingMode = !editingMode">edit</button>
<input v-else type="text" value ref="input">
export default {
  name: "App",
  components: {
    HelloWorld
  },
  data: function() {
    return {
      editingMode: false
    };
  },
  methods: {
    onClickButton() {
      this.editingMode = true;
      this.$refs.input.focus();
    }
  }
};

🌎 Fiddle

Problem

Because re-rendering in Vue synchronous, when we calling this.$refs.input.focus(), input field could be not rendered yet. I experienced two cases:

  1. Input is not mounted yet. In this case, Error in v-on handler: "TypeError: Cannot read property 'focus' of undefined" will occur.
  2. No this error, but no focus too. It looks like there is the interval between input field mounted and ready to manipulations.

Upvotes: 2

Views: 2366

Answers (1)

alt146
alt146

Reputation: 526

Try calling it in this.$nextTick :

methods: {
  onClickButton() {
    this.editingMode = true;
    this.$nextTick(() => {
      this.$refs.input.focus();
    })
  }
}

https://codesandbox.io/s/sleepy-dew-5mcju

Upvotes: 5

Related Questions