Rozgonyi
Rozgonyi

Reputation: 1059

How you do you call a method once rendering is done in Vue?

I have am building a Vue app that includes a QuillJS editor in a tab. I have a simple setTab(tabName) Vue method that shows/hides tabs with the v-if directive.

methods: {
  setTab: function (tabName) {
    this.view = tabName;
    if(tabName === 'compose') {
      var editor = new Quill('#editor', {
        modules: { toolbar: '#toolbar' },
        theme: 'snow'
      });
    }
  }
}

My tab is basically like this:

<div id="composer" v-if="tabName === 'compose'">
  <!-- toolbar container -->
  <div id="toolbar">
    <button class="ql-bold">Bold</button>
    <button class="ql-italic">Italic</button>
  </div>
  <!-- editor container -->
  <div id="editor">
    <p>Hello World!</p>
  </div>
</div>

Currently, I'm getting an error because the #editor element does not yet exist when I am calling new Quill(...). How do I delay that QuillJS initialization on the page so that it doesn't happen until after the #editor is already there?

Upvotes: 2

Views: 6082

Answers (3)

tony19
tony19

Reputation: 138336

Use this.$nextTick() to defer a callback to be executed after the next DOM update cycle (e.g., after changing a data property that causes a render-update).

For example, you could do this:

methods: {
  setTab: function (tabName) {
    this.view = tabName;
    if(tabName === 'compose') {
      this.$nextTick(() => {
        var editor = new Quill('#editor', {
          modules: { toolbar: '#toolbar' },
          theme: 'snow'
        });
      })
    }
  }
}

Upvotes: 4

Krantisinh
Krantisinh

Reputation: 1729

Use mounted hook.

mounted: function () {
  // Code that will run only after the
  // entire view has been rendered
}

Upvotes: 4

Estus Flask
Estus Flask

Reputation: 222538

A clean way to do this is not to rely on selectors but make Quill editor a self-contained component:

<template>
    <div class="quill-editor">
      <!-- toolbar container -->
      <div ref="toolbar">
        <button class="ql-bold">Bold</button>
        <button class="ql-italic">Italic</button>
      </div>
      <!-- editor container -->
      <div ref="editor">
        <p>Hello World!</p>
      </div>
    </div>
</template>

<script>
  ...
  name: "QuillEditor",
  mounted() {
    this.quill = new Quill(this.$refs.editor, {
      modules: { toolbar: this.$refs.toolbar },
      theme: 'snow'
    });
  }
  ...
</script>

Upvotes: 1

Related Questions