I'm facing a problem using nextTick() in Vue.
Here is 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();
}
}
}
Of course this.$refs.theInput
is not rendered yet when I ask to focus in it.
So far, the only way I've figured out how to make it work is to add a timeout, which is a very bad solution :
methods: {
toggle() {
this.editing = ! this.editing;
if (this.editing) {
setTimeout(() => this.$refs.theInput.focus(), 100)
}
}
}
Trying to make it more clean I tried this, but the result is the same :
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 trying to focus on theInput ? Thanks for your help.
I'm facing a problem using nextTick() in Vue.
Here is 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();
}
}
}
Of course this.$refs.theInput
is not rendered yet when I ask to focus in it.
So far, the only way I've figured out how to make it work is to add a timeout, which is a very bad solution :
methods: {
toggle() {
this.editing = ! this.editing;
if (this.editing) {
setTimeout(() => this.$refs.theInput.focus(), 100)
}
}
}
Trying to make it more clean I tried this, but the result is the same :
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 trying to focus on theInput ? Thanks for your help.
Share asked Feb 26, 2020 at 13:58 JoulssJoulss 1,1893 gold badges14 silver badges26 bronze badges1 Answer
Reset to default 4Found it, $nextTick wasn't at the good place. Move it like this works :
methods: {
toggle() {
this.editing = ! this.editing;
this.$nextTick(() => {
if (this.editing) {
this.$refs.theInput.focus();
};
});
}
}