admin管理员组文章数量:1332865
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();
};
});
}
}
本文标签: javascriptVuejs thisnextTick() doesn39t seems to wait for dom renderingStack Overflow
版权声明:本文标题:javascript - Vue.js this.$nextTick() doesn't seems to wait for dom rendering - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742293121a2448185.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论