Vue3 封装 vue-quill 富文本组件

1、组件效果(实现图片上传、工具栏鼠标悬浮提示)

2、安装插件

npm install @vueup/vue-quill

3、components -> TextEditor.vue(富文本组件)

<template>
  <quill-editor ref="editorRef" v-model:content="content" :options="options" contentType="html"></quill-editor>
</template>

<script setup lang="ts">
  import { onMounted, ref,toRaw,nextTick  } from 'vue'
  import filesApi from '@/api/files';
  import { ElMessage } from 'element-plus'
  import { Quill, QuillEditor } from '@vueup/vue-quill'
  import '@vueup/vue-quill/dist/vue-quill.snow.css'
  import axios from 'axios';


  const content=ref()
  const editorRef=ref()

  // 处理富文本图片上传
  const imageHandler = () => {
    // 创建一个文件输入元素
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    // 模拟点击,打开文件选择对话框
    input.click();

    // 当用户选择文件后触发的事件
    input.onchange = async () => {
      // 获取用户选择的文件
      const file = input.files ? input.files[0] : null;
      if (file) {
        // 创建一个 FormData 对象,用于文件上传
        const formData = new FormData();
        formData.append('file', file);

        try {
          // 使用 axios 发送 POST 请求,将文件上传到服务器
          const response = await axios.post(filesApi.url(), formData, { headers: { 'Content-Type': 'multipart/form-data' } });

          // 确保获取到 Quill 编辑器实例
          const quill = toRaw(editorRef.value).getQuill()
          if (quill) {
            // 获取当前光标位置
            const range = quill.getSelection(true);
            // 在当前光标位置插入上传的图片
            quill.insertEmbed(range.index, 'image', response.data.data);
          }
        } catch (error) {
          ElMessage.error("图片上传失败");
        }
      }
    };
  }

  let options = {
    modules: {
      toolbar: {
        container: [
          ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
          [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
          [{ align: [] }], // 对齐方式
          [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
          [{ font: [] }], // 字体种类
          [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
          // [{ direction: 'ltl' }], // 文本方向
          // [{ direction: 'rtl' }], // 文本方向
          [{ indent: '-1' }, { indent: '+1' }], // 缩进
          [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
          [{ script: 'sub' }, { script: 'super' }], // 上标/下标
          ['blockquote', 'code-block'], // 引用  代码块
          ['clean'], // 清除文本格式
          ['link', 'image', 'video'], // 链接、图片、视频
        ],
        handlers: {
          image: imageHandler,
        },
      },
    }
  }

  // toolbar标题
  const titleConfig = [
    { Choice: '.ql-insertMetric', title: '跳转配置' },
    { Choice: '.ql-bold', title: '加粗' },
    { Choice: '.ql-italic', title: '斜体' },
    { Choice: '.ql-underline', title: '下划线' },
    { Choice: '.ql-header', title: '段落格式' },
    { Choice: '.ql-strike', title: '删除线' },
    { Choice: '.ql-blockquote', title: '块引用' },
    { Choice: '.ql-code', title: '插入代码' },
    { Choice: '.ql-code-block', title: '插入代码段' },
    { Choice: '.ql-font', title: '字体' },
    { Choice: '.ql-size', title: '字体大小' },
    { Choice: '.ql-list[value="ordered"]', title: '编号列表' },
    { Choice: '.ql-list[value="bullet"]', title: '项目列表' },
    { Choice: '.ql-direction', title: '文本方向' },
    { Choice: '.ql-header[value="1"]', title: 'h1' },
    { Choice: '.ql-header[value="2"]', title: 'h2' },
    { Choice: '.ql-align', title: '对齐方式' },
    { Choice: '.ql-color', title: '字体颜色' },
    { Choice: '.ql-background', title: '背景颜色' },
    { Choice: '.ql-image', title: '图像' },
    { Choice: '.ql-video', title: '视频' },
    { Choice: '.ql-link', title: '添加链接' },
    { Choice: '.ql-formula', title: '插入公式' },
    { Choice: '.ql-clean', title: '清除字体格式' },
    { Choice: '.ql-script[value="sub"]', title: '下标' },
    { Choice: '.ql-script[value="super"]', title: '上标' },
    { Choice: '.ql-indent[value="-1"]', title: '向左缩进' },
    { Choice: '.ql-indent[value="+1"]', title: '向右缩进' },
    { Choice: '.ql-header .ql-picker-label', title: '标题大小' },
    { Choice: '.ql-header .ql-picker-item[data-value="1"]', title: '标题一' },
    { Choice: '.ql-header .ql-picker-item[data-value="2"]', title: '标题二' },
    { Choice: '.ql-header .ql-picker-item[data-value="3"]', title: '标题三' },
    { Choice: '.ql-header .ql-picker-item[data-value="4"]', title: '标题四' },
    { Choice: '.ql-header .ql-picker-item[data-value="5"]', title: '标题五' },
    { Choice: '.ql-header .ql-picker-item[data-value="6"]', title: '标题六' },
    { Choice: '.ql-header .ql-picker-item:last-child', title: '标准' },
    { Choice: '.ql-size .ql-picker-item[data-value="small"]', title: '小号' },
    { Choice: '.ql-size .ql-picker-item[data-value="large"]', title: '大号' },
    { Choice: '.ql-size .ql-picker-item[data-value="huge"]', title: '超大号' },
    { Choice: '.ql-size .ql-picker-item:nth-child(2)', title: '标准' },
    { Choice: '.ql-align .ql-picker-item:first-child', title: '居左对齐' },
    { Choice: '.ql-align .ql-picker-item[data-value="center"]', title: '居中对齐' },
    { Choice: '.ql-align .ql-picker-item[data-value="right"]', title: '居右对齐' },
    { Choice: '.ql-align .ql-picker-item[data-value="justify"]', title: '两端对齐' }
  ]

  // 给富文本框工具栏加上鼠标悬浮中文提示
  const initTitle = () => {
    for (let item of titleConfig) {
      // .editor 是富文本编辑器的类名
      let tip = document.querySelector('.editor ' + item.Choice);
      if (tip) {
        tip.setAttribute('title', item.title);
      }
    } 
  }

  onMounted(async()=>{
    // 确保 Quill 编辑器已完全加载
    await nextTick();
    // 初始化工具栏的中文提示
    initTitle();
  })

</script>

<style scoped lang="less">

</style>

4、如何使用 TextEditor 组件

<template>
    <div class="editor">
        <TextEditor v-model:content="articleModel.content" />
    </div>
</template>

<script setup lang="ts">
import TextEditor from '@/components/TextEditor.vue';

</script>

<style scoped lang="less">
  .editor{
    width: 100%;
    :deep(.ql-editor) {
      min-height: 200px;
    }
  }
</style>

5、I have a question

         Vue 3 + ts 中富文本组件如何实现图片大小缩放?

好的,以下是一个使用 Vue 3 封装富文本编辑器的完整代码示例。这里使用了 Quill.js 作为富文本编辑器库,你需要先安装 Quill.js: ``` npm install quill ``` 然后你可以创建一个名为 `RichTextEditor.vue` 的组件,代码如下: ```vue <template> <div ref="editor"></div> </template> <script> import Quill from &#39;quill&#39;; import &#39;quill/dist/quill.snow.css&#39;; export default { name: &#39;RichTextEditor&#39;, props: { value: { type: String, default: &#39;&#39; }, options: { type: Object, default: () => ({}) } }, mounted() { this.quill = new Quill(this.$refs.editor, this.options); this.quill.on(&#39;text-change&#39;, this.handleTextChange); this.quill.setContents(this.quill.clipboard.convert(this.value)); }, beforeUnmount() { this.quill.off(&#39;text-change&#39;, this.handleTextChange); this.quill = null; }, methods: { handleTextChange() { this.$emit(&#39;input&#39;, this.quill.root.innerHTML); } } }; </script> ``` 在这个组件中,我们首先引入了 Quill.js 库和样式文件。然后,在 `mounted` 生命周期中,我们创建了一个 Quill 实例,并将其附加到组件的 `div` 元素上。我们还监听了 `text-change` 事件,以便在文本发生变化时更新组件的 `value` 属性。 在父组件中,你可以使用 `RichTextEditor` 组件来创建一个富文本编辑器,例如: ```vue <template> <div> <RichTextEditor v-model="content" :options="editorOptions" /> </div> </template> <script> import RichTextEditor from &#39;./RichTextEditor.vue&#39;; export default { name: &#39;MyComponent&#39;, components: { RichTextEditor }, data() { return { content: &#39;&#39;, editorOptions: { modules: { toolbar: [ [{ header: [1, 2, false] }], [&#39;bold&#39;, &#39;italic&#39;, &#39;underline&#39;], [&#39;image&#39;, &#39;code-block&#39;] ] }, scrollingContainer: &#39;body&#39; } }; } }; </script> ``` 在这个示例中,我们在父组件中使用 `RichTextEditor` 组件,并将其绑定到 `content` 数据中。我们还传递了一个 `options` 属性,以便配置富文本编辑器的选项。在这里,我们仅显示了一些基本的工具栏按钮,以便对文本进行格式化和插入图片。 当用户在富文本编辑器中输入或修改文本时,`content` 数据会自动更新。你可以在提交表单或保存数据时使用这个数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值