Having trouble with nextTick() in Vue.
Here's the template code: In the template:
<template>
<div>
<div v-if="editing">
<span ref="theInput"
contenteditable="true">{{ someValue }}</span>
</div>
<div v-else>
<span>{{ someValue }}</span>
</div>
...
</template>
And the script code:
data() {
editing: false
}
...
methods: {
toggle() {
this.editing = ! this.editing;
if (this.editing) {
this.$refs.theInput.focus();
}
}
}
When trying to focus on this.$refs.theInput
, it's not rendered yet.
My current workaround involves adding a timeout, but I know it's not the best solution:
methods: {
toggle() {
this.editing = ! this.editing;
if (this.editing) {
setTimeout(() => this.$refs.theInput.focus(), 100)
}
}
}
I also attempted a cleaner approach using this.$nextTick()
, but encountered the same issue:
methods: {
toggle() {
this.editing = ! this.editing;
if (this.editing) {
this.$nextTick(() => {
this.$refs.theInput.focus();
});
}
}
}
Shouldn't nextTick()
wait for the DOM to render before focusing on theInput
?
Appreciate any help you can provide.