Vue3 中如何使用 vueup/vue-quill 富文本并限制输入字数

2025-01-10 19:55:06   小编

在Vue 3项目中,使用vueup/vue - quill富文本编辑器并限制输入字数是一个常见需求。下面我们就来详细探讨如何实现这一功能。

安装vueup/vue - quill。在项目目录下打开终端,运行命令npm install vueup/vue - quill --save,将其添加到项目依赖中。

安装完成后,在Vue组件中引入并使用。在组件的<script setup>标签内,导入组件和样式:

import VueQuillEditor from 'vueup/vue - quill';
import 'vueup/vue - quill/dist/vue-quill.snow.css';

然后在模板部分使用该组件:

<template>
  <VueQuillEditor ref="quillRef" :options="editorOptions" @editor-change="onEditorChange" />
</template>

这里,quillRef是富文本编辑器的引用,editorOptions是编辑器的配置选项,@editor-change是监听编辑器内容变化的事件。

接下来配置editorOptions

import { ref } from 'vue';

const quillRef = ref(null);
const editorOptions = {
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code - block'],
      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      ['link', 'image'],
      ['clean']
    ]
  }
};

上述配置设置了富文本编辑器的主题为snow,并定义了工具栏中的各种功能按钮。

现在来实现限制输入字数的功能。通过@editor-change事件来监听内容变化:

const maxLength = 100; // 设定最大字数
const contentLength = ref(0);

const onEditorChange = (content) => {
  const text = quillRef.value?.getText() || '';
  contentLength.value = text.length;
  if (contentLength.value > maxLength) {
    const excess = contentLength.value - maxLength;
    quillRef.value.deleteText(text.length - excess, excess);
  }
};

onEditorChange方法中,首先获取编辑器中的文本内容并更新当前字数。如果字数超过设定的最大字数,计算超出部分并删除多余的字符。

通过上述步骤,我们在Vue 3项目中成功集成了vueup/vue - quill富文本编辑器,并实现了输入字数限制功能。这样,用户在使用富文本编辑器时,输入的内容将不会超过我们设定的字数上限,满足了项目中的特定需求。无论是用于文章撰写、评论输入等场景,都能很好地控制输入内容的长度。

TAGS: VUE3开发 Vue3富文本 vueup/vue - quill 富文本字数限制

欢迎使用万千站长工具!

Welcome to www.zzTool.com