[Vuejs]-How can I set character limit in quill editor in Vue.JS

0👍

A potential solution I found on GitHub.

To transform it to Vue, you have to define it as a function (for simplicity I am doing it in a Composition API script setup but it should be easy enough to convert to whatever you prefer) and create a ref for the editor:

<script setup>
import { ref } from 'vue';

const quill = ref();
const limit = 256;

function checkLength(delta, old, source) {
  if (quill.value.getQuill().getLength() <= limit) {
    return;
  }
  const { ops } = delta.delta;
  let updatedOps;
  if (ops.length === 1) {
    // text is inserted at the beginning
    updatedOps = [{ delete: ops[0].insert.length }];
  } else {
    // ops[0] == {retain: numberOfCharsBeforeInsertedText}
    // ops[1] == {insert: "example"}
    updatedOps = [ops[0], { delete: ops[1].insert.length }];
  }
  quill.value.getQuill().updateContents({ ops: updatedOps });
}
</script>

And add an event listener and the ref to the component:

<quill-editor ref="quill" @textChange="checkLength" :options="options" />

Leave a comment