WangEditor添加上传附件功能 vue3

文章讲述了如何在WangEditor中正确配置并注册上传附件插件,以避免二次编辑时出现错误。关键步骤包括在main.ts中全局注册插件,设置编辑器配置以处理附件节点的菜单,以及实现自定义上传功能,利用上传接口将文件插入到富文本编辑器中。
摘要由CSDN通过智能技术生成

看官方文档要求 @WangEditor/editor 版本 >=5.1.16

下载上传附件的插件

yarn add @wangeditor/plugin-upload-attachment

首先要注册到编辑器,如果把下面的代码写在WangEditor的组件里出现第一次使用编辑没问题,但是第二次编辑会报错的问题,那么可能是多次注册引起的,将下面的注册代码写在main.ts文件里。

import { Boot } from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'

// 注册。要在创建编辑器之前注册,且只能注册一次,不可重复注册。
Boot.registerModule(attachmentModule)

然后在

import { IToolbarConfig, IEditorConfig } from "@wangeditor/editor";
const editorConfig: Partial<IEditorConfig> = {
        
  // 在编辑器中,点击选中“附件”节点时,要弹出的菜单
  hoverbarKeys: {
    attachment: {
      menuKeys: ['downloadAttachment'], // “下载附件”菜单
    },
  },
  MENU_CONF: {
/**
 * @description 附件自定义上传
 * @param file 上传的文件
 * @param insertFn 上传成功后的回调函数(插入到富文本编辑器中)
 * */
         uploadAttachment: {
            customUpload(file: File, insertFn: Function) {
			let formData = new FormData();
			formData.append("files", file);
			upload(formData).then(res => {   //upload是上传附件接口
				if (res.success) {
					console.log(res.data);       //defaultconfigUrl是接口地址             
					insertFn(`${res.data[0].fileName}`, defaultconfigUrl +      
                           res.data[0]!.fileUrl);
				}
			});
	    }
        
  }
};

//工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
  // 插入哪些菜单
  insertKeys: {
    index: 0, // 自定义插入的位置
    keys: ['uploadAttachment'], // “上传附件”菜单
  },

}

最后效果

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值