wangEditor/editor自定义粘贴后续

发布于:2025-02-11 ⋅ 阅读:(57) ⋅ 点赞:(0)

背景

按照上一篇文章处理自定义粘贴之后,发现复制表格之后,会出现表格样式失效问题,原因是自定义粘贴没有处理表格数据,导致按照文本格式粘贴了

处理方式

  • 自定义表格(如果业务有需求需要更新表格样式的,那就要研究一下wangEditor/editor的table-module的部分源码熟悉node的数据结构)非必要不需要这样
  • 自定义粘贴中,忽略含有表格数据的粘贴(本文采用方式)

代码如下

utils/index.js

/**
 * 自定义粘贴
 * @description 富文本自定义粘贴
 * @returns {boolean} 是否不阻止默认粘贴行为
 */
export function customPasteItemFunc(editor, event) {
  try {
    /** 粘贴事件 */
    const clipboardData = event.clipboardData;
    const html = clipboardData.getData("text/html");
    /** 正则匹配table标签 */
    const res = html.match(/<table[^>]+>/g);
    if (res) {
      return true;
    }
    if (clipboardData && clipboardData.items) {
      for (let i = 0; i < clipboardData.items.length; i++) {
        const item = clipboardData.items[i];
        // 如果是由图片文件
        if (item.type.indexOf("image") !== -1) {
          customUploadImage.call(this, item, editor);
          return false;
        }
        // 如果是由视频文件
        else if (item.type.indexOf("video") !== -1) {
          customUploadVideo.call(this, item, editor);
          return false;
        } else if (item.type.indexOf("text/html") !== -1 && !res) {
          customPasteTextMain.call(this, clipboardData, editor);
          return false;
        }
      }
    }
    return false;
  } catch (e) {
    this.$Message.error(e.message);
  }
}

edit.vue

<template>
	<Editor
      ...
      @customPaste="handleCustomPaste"
    />
</template>
methods: {
 handleCustomPaste(editor, event) {
      const isStop = customPasteItemFunc.call(this, editor, event);
      // 阻止默认的粘贴行为
      if (!isStop) event.preventDefault();
      return isStop;
    }
}

核心思路

是否阻止粘贴事件的默认行为
wangeditor/editor中针对在自定义粘贴事件中阻止默认粘贴行为,需要使用如下代码

function customPaste(editor, event) {
	/** 相关业务处理 */
	...
	// 阻止默认行为
	event.preventDefault();
	return false;
}

总结

书接上文,大家只看这篇的可以翻看上一节,如果有帮助到大家,记得帮博主点个赞!!!


网站公告

今日签到

点亮在社区的每一天
去签到