How can I set character limit in quill editor in Vue.JS

741 Views Asked by At

I'm having a quill editor, how can limit the user to enter maximum 256 characters?

<template>
  <div>
    <quill-editor :options="options" " v-model="form.content_vn" />
  </div>

<script>
options: {
  modules: {
    toolbar: [
      "bold",
      "italic",
      "underline",
      "clean",
      {
        align: []
      },
     ],
  },
  readOnly: false,
  theme: "snow",
},
</script>
</template>

I have tried to use an event @keyup="checkInputLength" and @keydown="checkInputLength" with this method:

checkInputLength(event) {
    const input = event.target;
    const inputValue = input.value.replace(/\s/g, '');
    const maxLength = 10;

    if (inputValue.length >= maxLength) {
        event.preventDefault();
    input.value = inputValue.slice(0, maxLength);
    }
},
1

There are 1 best solutions below

2
Ansis Spruģevics On

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" />