wangeditor自定义粘贴

背景

说起来这个事情,那还是源于年前需求,由于急需打造公司自己的文档中心且不启用新的项目的前提下,在选取富文本编辑器这一步,果断选择了wangeditor这个插件,没有考虑粘贴这种问题,在使用的过程中,不舒适度极高,无奈之下接到了优化需求,进行自定义粘贴改造。

技术栈

  • vue2.x
  • @wangeditor/editor@5.1.x

自定义粘贴

官网,已经给出了自定义粘贴的入口,点击这里

我们需要处理的,就是针对复制媒体文件和带有格式的文本进行特殊处理

  1. 带有格式的文本,不保留原有格式,纯粘贴文本;
  2. 图片等媒体资源,可支持粘贴

可能出现的问题及解决方案

  • 编辑器中通过insertNode插入媒体文件之后,执行insertText失效 - 插入一个空段落即可(下面代码中有示例)
  • 如何读取剪切板 中,含有的本地原生文件 ,(复制图片怎么读取) - clipboardData.items 中,获取每一项的item.getAsFile()
  • 富文本编辑器 中,怎么初始化 修改插入视频的大小 ? - insertNode(video), 核心是使用该api去插入一个视频节点,它的数据结构中加入width和height的值即可,(下面代码中有示例)
  • 请使用 '@customPaste',不要放在 props 中。。。 - 出现类似的报错,请不要在config中使用customPaste而是用组件上的方法,改文章后续有使用示例代码

代码

大家期待的代码环节,

javascript 复制代码
/** 异步等待 */
function sleep(delay) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, delay);
  });
}

/**
 * 插入一个空段落
 * @description 为了插入图片/视频后,光标不被图片覆盖
 * @param {*} editor
 */
function insertPragraph(editor) {
  const p = { type: "paragraph", children: [{ text: "" }] };
  editor.insertNode(p);
}

/**
 * 自定义粘贴
 * @description 富文本自定义粘贴
 */
export async function customPasteItemFunc(editor, event) {
  try {
    /** 粘贴事件 */
    const clipboardData = event.clipboardData;
    if (clipboardData && clipboardData.items) {
      for (let i = 0; i < clipboardData.items.length; i++) {
        const item = clipboardData.items[i];
        if (item.type.indexOf("image") !== -1) {
          /** 粘贴图片 */
          const file = item.getAsFile();
          if (file) {
            const notify = this.$notify({
              title: '提示',
              message: '当前有正在上传的媒体文件',
              duration: 0,
              showClose: false,
              type: 'warning'
            });
            const { code, data } = await uploadFile(file);
            notify.close();
            if (code !== 0) {
              throw new Error("图片上传失败");
            }
            const elem = {
              type: "image",
              src: data.url,
              alt: "bvox",
              href: "",
              children: [{ text: "" }], // void node 必须包含一个空 text
            };
            editor.insertNode(elem); // 插入图片
            insertPragraph(editor); // 插入一个空段落
          }
        }
        // 如果是由视频文件
        else if (item.type.indexOf("video") !== -1) {
          const file = item.getAsFile();
          if (file) {
            const notify = this.$notify({
              title: '提示',
              message: '当前有正在上传的媒体文件',
              duration: 0,
              showClose: false,
              type: 'warning'
            });
            const { code, data } = await uploadFile(file);
            notify.close();
            if (code !== 0) {
              throw new Error("视频上传失败");
            }
            const elem = {
              type: "video",
              src: data.url,
              poster,
              width: 530,
              height: 220,
              children: [{ text: "" }],
            };
            editor.insertNode(elem); // 插入视频
            insertPragraph(editor); // 插入一个空段落
          }
        } else if (item.type.indexOf("text/html") !== -1) {
          // 自定义复制
          const html = clipboardData.getData("text/html");
          const text = clipboardData.getData("text/plain");
          const resultImgs = html.match(/<img[^>]+>/g);
          const imgNodes = [];
          // 将匹配到的所有图片插入到编辑器中
          if (resultImgs) {
            resultImgs.forEach((img) => {
              const imgUrl = img.match(/src="([^"]+)"/)[1];
              const elem = {
                type: "image",
                src: imgUrl,
                alt: "bvox",
                href: "",
                children: [{ text: "" }], // void node 必须包含一个空 text
              };
              imgNodes.push(elem);
            });
          }
          // 多图插入
          const positions = text.split("\n");
          if (positions.length > 1) {
            for (let i = 0; i < positions.length; i++) {
              if (positions[i] === "[图片]") {
                editor.insertNode(imgNodes.shift());
                insertPragraph(editor); // 插入一个空段落
                await sleep(1000);
              } else {
                editor.insertText(positions[i]);
                await sleep(300);
              }
            }
          }
        }
      }
    }
  } catch (e) {
    this.$Message.error(e.message);
  }
}

大家疑惑的地方

  1. 为什么代码中直接出现this.$Message.error()? 答: customPasteItemFunc.call(this, editor, event);
  2. 怎么使用这个方法呢? 答:只说在vue中的使用,react自行去看官网使用即可,
javascript 复制代码
<Editor
  ....
  @customPaste="handleCustomPaste"
/>

method: {
  handleCustomPaste(editor, event) {
      customPasteItemFunc.call(this, editor, event);
      // 阻止默认的粘贴行为
      event.preventDefault()
      return false;
    }
}

写在最后

看到这里的,大家帮博主点个赞再走呗,制作不易,如果大家有什么其他的需求或者疑问,可以私信或者评论区见,感谢大家支持!!!

相关推荐
仰望.3 小时前
vue 表格组件 vxe-table 树表格懒加载支持拖拽排序的详细用法
前端·javascript·vue.js·vxe-table
康小旺8 小时前
AI 写 Vue 总写成同一个味道:给它装 Skills,装的不是知识是边界
vue.js·typescript
徐小夕9 小时前
JitKnow AI知识库 4.7 发布|多文档推理+拖拽 Agent + 技能库,打造更懂业务的 AI 知识中台
前端·vue.js·github
u01110267512 小时前
Canvas 导出 PNG 时 quality 参数为什么不起作用
前端·javascript·vue.js
计算机编程-吉哥14 小时前
计算机毕业设计 基于 SpringBoot + Vue 的剧本杀系统 Java毕业设计【任务书、开题报告、中期报告、论文、源码】
java·vue.js·spring boot·毕业设计·课程设计·计算机毕业设计选题
这里是杨杨吖14 小时前
SpringCloud+Vue民宿房屋租赁系统 附带详细运行指导视频
vue.js·spring boot·spring cloud·房屋·民宿租赁
小大宇1 天前
Vue知识点6-computed计算属性
前端·javascript·vue.js
程序员海军1 天前
尤雨溪 : Vue 4 已经在规划中了!
前端·javascript·vue.js
徐小夕1 天前
doc2docx方案,开源!
前端·vue.js·github
徐小夕1 天前
JitOFD:一款面向信创与档案场景的 Web 端 OFD 编辑器
前端·vue.js·github