Reputation: 915
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();
}
}
};
Because re-rendering in Vue synchronous, when we calling this.$refs.input.focus()
, input field could be not rendered yet. I experienced two cases:
Error in v-on handler: "TypeError: Cannot read property 'focus' of undefined"
will occur.Upvotes: 2
Views: 2366
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