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;
    }
}

写在最后

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

相关推荐
JIngJaneIL8 小时前
基于java + vue校园快递物流管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js
OpenTiny社区10 小时前
2025OpenTiny星光ShowTime!年度贡献者征集启动!
前端·vue.js·低代码
狗哥哥10 小时前
从零到一:打造企业级 Vue 3 高性能表格组件的设计哲学与实践
前端·vue.js·架构
计算机毕设VX:Fegn089510 小时前
计算机毕业设计|基于springboot + vue图书借阅管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
褪色的笔记簿11 小时前
在 Vue 项目里管理弹窗组件:用 ref 还是用 props?
前端·vue.js
一只小阿乐11 小时前
前端vue3 web端中实现拖拽功能实现列表排序
前端·vue.js·elementui·vue3·前端拖拽
AAA阿giao11 小时前
从“操纵绳子“到“指挥木偶“:Vue3 Composition API 如何彻底改变前端开发范式
开发语言·前端·javascript·vue.js·前端框架·vue3·compositionapi
专注前端30年11 小时前
在日常开发项目中Vue与React应该如何选择?
前端·vue.js·react.js
进击的野人12 小时前
Vue 组件与原型链:VueComponent 与 Vue 的关系解析
前端·vue.js·面试
馬致远12 小时前
Vue todoList案例 优化之本地存储
前端·javascript·vue.js