最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue.js this.$nextTick() doesn't seems to wait for dom rendering - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 4

Found 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();
      };
    });
  }
}
发布评论

评论列表(0)

  1. 暂无评论