wangEditor 自定义悬浮菜单

1,218 阅读1分钟
一点探索的记录,最终这个功能没有用上,希望对你有帮助,不对的地方欢迎沟通交流(╹▽╹)
参考文章

想要实现的效果

image.png 点击附件时显示下载和预览选项,下载可通过指定方法添加,预览的按钮则需要使用自定义.

  • 下载附件
import attachmentModule from '@wangeditor/plugin-upload-attachment';

Boot.registerModule(attachmentModule);
const attachmentToHtmlConf = {
  type: 'attachment',
  elemToHtml: function imageToHtml(elemNode: any) {
    const { fileName, link } = elemNode || {};
    return `<a href="${link}" class="upload-file wangDownFile" data-w-e-type="attachment" data-w-e-is-void data-w-e-is-inline download="${fileName}"><span class="iconfont icon-wenjian upload-file-icon"></span>${fileName}</a>`;
  },
};
Boot.registerElemToHtml(attachmentToHtmlConf);

const toolbarConfig: any = {
    excludeKeys: [
      'group-video', //视频
    ],
    insertKeys: {
      index: 0, // 自定义插入的位置
      keys: ['uploadAttachment'], // “上传附件”菜单
    },
  };
  const editorConfig: any = {
    placeholder: '请输入内容...',
    hoverbarKeys: {
      attachment: {
        menuKeys: ['downloadAttachment', 'myMenuIndent'], // “下载附件”菜单
      },
    },
    MENU_CONF: {
      uploadImage: {
        base64LimitSize: 1024 * 1024,
      },
      uploadAttachment: {
        // 用户自定义上传
        customUpload: async (file: File, insertFn: any) => {
          try {
            const fd = new FormData();
            fd.append('file', file);
            const res = await fileUpload(fd);
            const src = `${baseUrl}/management/download?fileName=${res.fileName}&path=${res.path}`;
            // const src = `http://localhost:8001/cn/management/download?fileName=${res.fileName}&path=${res.path}`;
            insertFn(res.fileName, src);
          } catch (err) {
            message.error('上传失败');
          }
        },
      },
    },
  };
  • 预览附件
//customMenu.ts
class CustomMenu {
  // JS 语法
  constructor(editor: any) {
    (this.title = '预览'), (this.tag = 'button');
  }
  // 下拉框的选项
  getOptions(editor: any) {
    // JS 语法
    return false;
  }
  // 菜单是否需要激活(如选中加粗文本,“加粗”菜单会激活),用不到则返回 false
  isActive(editor: any) {
    // JS 语法
    return false;
  }
  // 获取菜单执行时的 value ,用不到则返回空 字符串或 false
  getValue(editor: any) {
    // JS 语法
    return 'addIndent'; // 匹配 options 其中一个 value
  }
  // 菜单是否需要禁用(如选中 H1 ,“引用”菜单被禁用),用不到则返回 false
  isDisabled(editor: any) {
    // JS 语法
    return false;
  }
  // 点击菜单时触发的函数
  exec(editor: any, value: any) {
    // JS 语法
    console.log('点击附件', editor, value);
    //做相关操作
  }
}
export default CustomMenu;
import CustomMenu from './customMenu';
const myMenu: any = {
  key: 'myMenu', // 定义 menu key :要保证唯一、不重复(重要)
  factory() {
    return new CustomMenu(this); 
  },
};
Boot.registerMenu(myMenu);
const editorConfig ={
//......其他代码
    hoverbarKeys: {
          attachment: {
            menuKeys: ['downloadAttachment', 'myMenuIndent'], // “下载附件”菜单
          },
        },
 //......其他代码
}