How to use v-model in quill.js in vue 3?

by cortez.connelly , in category: Javascript , 3 months ago

How to use v-model in quill.js in vue 3?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 3 months ago

@cortez.connelly 

To use v-model with Quill.js in Vue 3, you can create a custom component that wraps the Quill editor and uses the v-model directive to bind the editor's content to a data property in your component. Here's an example of how you can achieve this:

  1. First, install Quill and import it in your Vue component:
1
npm install quill


1
import Quill from 'quill';


  1. Create a custom component called QuillEditor.vue:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<template>
  <div>
    <div ref="editor"></div>
  </div>
</template>

<script>
export default {
  props: ['value'],
  mounted() {
    this.quill = new Quill(this.$refs.editor, {
      theme: 'snow'
    });

    this.quill.on('text-change', () => {
      this.$emit('input', this.quill.root.innerHTML);
    });

    if (this.value) {
      this.quill.root.innerHTML = this.value;
    }
  },
  watch: {
    value: function(newValue) {
      if (this.quill && this.quill.root.innerHTML !== newValue) {
        this.quill.root.innerHTML = newValue;
      }
    }
  }
};
</script>


  1. Use the QuillEditor component in your parent component and bind the content of the editor using v-model:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<template>
  <div>
    <quill-editor v-model="content" />
  </div>
</template>

<script>
import QuillEditor from './QuillEditor.vue';

export default {
  components: {
    QuillEditor
  },
  data() {
    return {
      content: ''
    };
  }
};
</script>


By using the v-model directive in the parent component, changes made in the Quill editor will be automatically synced to the content data property, and changes to the content data property will be reflected in the editor.