我在Vue中使用nextTick()遇到问题。
这是模板代码: 在模板中:
<template>
<div>
<div v-if="editing">
<span ref="theInput"
contenteditable="true">{{ someValue }}</span>
</div>
<div v-else>
<span>{{ someValue }}</span>
</div>
...
</template>
还有脚本代码:
data() {
editing: false
}
...
methods: {
toggle() {
this.editing = ! this.editing;
if (this.editing) {
this.$refs.theInput.focus();
}
}
}
当我要求重点关注this.$refs.theInput
时,当然还没有渲染。
到目前为止,我弄清楚如何使其工作的唯一方法是添加超时,这是一个非常糟糕的解决方案:
methods: {
toggle() {
this.editing = ! this.editing;
if (this.editing) {
setTimeout(() => this.$refs.theInput.focus(), 100)
}
}
}
试图使其更加干净,我尝试了此方法,但结果是相同的:
methods: {
toggle() {
this.editing = ! this.editing;
if (this.editing) {
this.$nextTick(() => {
this.$refs.theInput.focus();
});
}
}
}
nextTick是否应该等待dom渲染后再尝试将焦点放在Input上? 感谢您的帮助。
答案 0 :(得分:1)
找到它了,$ nextTick不在合适的位置。像这样工作:
methods: {
toggle() {
this.editing = ! this.editing;
this.$nextTick(() => {
if (this.editing) {
this.$refs.theInput.focus();
};
});
}
}