wangEditor v4的简单使用

news/2024/10/17 16:18:18/

当前文档是 wangEditor v4 版本的。

wangEditor v5 已经正式发布,可参考文档。

v5 发布之后,v4 将不再开发新功能。

介绍

English documentation

wangEditor4 —— 轻量级 web 富文本编辑器,配置方便,使用简单。

  • 官网:www.wangeditor.com
  • 文档:www.wangeditor.com/v4
  • 源码:github.com/wangeditor-team/wangEditor (欢迎 star)

1:npm 安装 wangeditor

wangeditor v4 npm i wangeditor --save

基本使用:

<div id="div1"><p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>
<script type="text/javascript">const E = window.wangEditorconst editor = new E('#div1')editor.create()
</script>

2:构建引入 wangeditor

import E from 'wangeditor'

3:创建html

<div ref="editorRef"></div>

根据 ref 设置 编辑器元素高度,实例化 wangeditor

const editorRef = ref()
editor = new E(editorRef.value)

4:配置菜单

默认情况下,显示所有菜单

 // 配置菜单栏,删减菜单,调整顺序
editor.config.menus = ['bold','head','link','italic','underline'
]
​

5:图片相关处理

5.1 上传图片限制

editor.config.uploadImgMaxLength = 3

5.2 上传图片大小限制

editor.config.uploadImgMaxSize: 10 * 1024 * 1024, // 10M

5.3 请求头的设置

uploadImgServer: props.action, // 配置 server 接口地址
uploadImgHeaders: {Authorization: `Bearer ${getPiniaToken()}`,'X-Requested-With': 'XMLHttpRequest',
},

5.4 上传请求接口

editor.config.customUploadImg = function (resultFiles, insertImgFn) {// resultFiles 是 input 中选中的文件列表// insertImgFn 是获取图片 url 后,插入到编辑器的方法
​// 上传图片,返回结果,将图片插入到编辑器中insertImgFn(imgUrl)
}

5.5 上传前的钩子函数

editor.config.uploadImgHooks = {// 上传图片之前before: function(xhr) {console.log(xhr)
​// 可阻止图片上传return {prevent: true,msg: '需要提示给用户的错误信息'}},// 图片上传并返回了结果,图片插入已成功success: function(xhr) {console.log('success', xhr)},// 图片上传并返回了结果,但图片插入时出错了fail: function(xhr, editor, resData) {console.log('fail', resData)},// 上传图片出错,一般为 http 请求的错误error: function(xhr, editor, resData) {console.log('error', xhr, resData)},// 上传图片超时timeout: function(xhr) {console.log('timeout')},// 图片上传并返回了结果,想要自己把图片插入到编辑器中// 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式,可使用 customInsertcustomInsert: function(insertImgFn, result) {// result 即服务端返回的接口console.log('customInsert', result)
​// insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可insertImgFn(result.data[0])}
}

如果使用了 customUploadImg 自定义上传事件,那么 wangeditor 其他的图片上传api将会失效,例如: uploadImgServeruploadImgHeadersuploadImgHooks

以上都是修改在 editor.config,可以直接在 定义一个对象在editor.config中,看自己的需求:

6:设置是否源码模式

wangeditor 4 不支持源码模式,但可以自定义新增菜单

wangeditor 中创建 dom,按照官方文档写法如下:

  constructor(editor: E) {// data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述const $elem = $(`<div class="w-e-menu" data-title="源码"><i style="font-style: normal">源码</i></div>`)super($elem, editor)}

给新增的dom菜单添加事件

// 菜单点击事件
clickHandler() {this.switchMode()this.tryChangeActive()
}

修改源码模式

enum Mode {// 源码模式Source = 'source',// 实时预览模式Live = 'live',
}

上面使用了枚举定义,也可以不需要做,看自己的使用方式

在这里判断模式状态

 this.mode = this.isSouceMode() ? Mode.Live : Mode.Source

重新设置编辑器内容

let html = this.editor.txt.html() || ''

切换为源码模式,替换内容

使用字符串replace()函数查找字符进行转换,输出为源码Html

html = html.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;')

源码转换为文本内容

 html = this.editor.txt.text().replace(/&lt;/gi, '<').replace(/&gt;/gi, '>').replace(/&nbsp;/gi, ' ')

菜单激活事件,每次切换菜单的时候要调用下wangeditor 方法,否则编辑器不知道你当前菜单(扩展)有哪些

tryChangeActive() {if (this.isSouceMode()) {this.active()} else {this.unActive()}}

其他,扩展菜单可以参考文档案例:https://codepen.io/xiaokyo-the-bold/pen/ZEpWBeo

7:案例

扩展菜单class

export default class sourceMenu extends BtnMenu {mode = Mode.Live
​constructor(editor: E) {const $elem = $(`<div class="w-e-menu" data-title="源码"><i style="font-style: normal">源码</i></div>`)super($elem, editor)}
​// 菜单点击事件clickHandler() {this.switchMode()this.tryChangeActive()}tryChangeActive() {if (this.isSouceMode()) {this.active()} else {this.unActive()}}
​isSouceMode() {return this.mode === Mode.Source}
​switchMode() {this.mode = this.isSouceMode() ? Mode.Live : Mode.Sourcelet html = this.editor.txt.html() || ''if (this.isSouceMode()) {html = html.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;')} else :html = this.editor.txt.text().replace(/&lt;/gi, '<').replace(/&gt;/gi, '>').replace(/&nbsp;/gi, ' ')}this.editor.txt.html(html)}
}

在页面加载时,初始化wangeditor配置

  editor.create()editor.txt.html(props.modelValue) // 初始化重新设置编辑器内容

部分代码

onMounted(() => {editor = new E(editorRef.value)// 扩展自定义【源码】菜单const sourceMenuKey = 'source'editor.menus.extend(sourceMenuKey, sourceMenu)// 配置Object.assign(editor.config, {zIndex: 1,focus: false,height: props.height,menus: [sourceMenuKey, // 源码菜单'head','bold','fontSize','fontName','italic','underline','strikeThrough','indent','lineHeight','foreColor','backColor','link','list','todo','justify','quote','emoticon','image',// 'video', // 移除视频菜单'table','code','splitLine','undo','redo',],uploadFileName: 'file',uploadImgParams: {path: props.path,},uploadImgServer: '', // 配置 server 接口地址uploadImgHeaders: {Authorization: 'token','X-Requested-With': 'XMLHttpRequest',},// 限制上传的最大图片数量uploadImgMaxLength: 2,// 单个文件的最大体积限制,默认为 10MuploadImgMaxSize: 5 * 1024 * 1024, // 5McustomUploadImg: (files: Blob[], insertImgFn: (path: string) => void) => {try {const imgData = new FormData()for (let i in files) {imgData.append(`file`, files[i])}// 请求接口,并通过   insertImgFn()函数 插入到编辑器中// imgUrl 是从接口返回的图片地址insertImgFn(imgUrl)} catch (error) {message.error('图片上传失败,请重新上传')}},
​uploadImgHooks: {customInsert: function (insertImgFn: (path: string) => void, res: Recordable) {// res即远程请求的response// insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可insertImgFn(res.data.path as string)},},onchange() {let sourceMenu = editor?.menus.menuList.find((item) => item.key === sourceMenuKey)emit('update:isActive', sourceMenu?.isActive)emit('update:modelValue', editor!.txt.html())},onblur() {lock = true},})editor.create()editor.txt.html(‘回显时的内容’) // 初始化重新设置编辑器内容watchEffect(() => {props.disabled ? editor?.disable() : editor?.enable()})
})
onBeforeUnmount(() => {editor!.destroy()editor = null
})


http://www.ppmy.cn/news/1341765.html

相关文章

二叉树可视化

二叉树可视化 运行演示代码和程序已上传二叉树知识平衡二叉树红黑树最优二叉搜索树哈夫曼树KD树B树和B树 参考 运行演示 学习二叉树总是脑补图像&#xff0c;实在是恶心&#xff0c;就想写一个能可视化的二叉树&#xff0c;结果没控制好&#xff0c;功能越想越多&#xff0c;先…

吴恩达机器学习 第一阶段

Machine Learning 大纲梳理 便于复习 2000字左右

网络时间协议NTP工作模式

单播服务器/客户端模式 单播服务器/客户端模式运行在同步子网中层数较高层上。这种模式下,需要预先知道服务器的IP地址。 客户端:运行在客户端模式的主机(简称客户端)定期向服务器端发送报文,报文中的Mode字段设置为3(客户端模式)。当客户端接收到应答报文时,客户端会…

【Oracle 集群】RAC知识图文详细教程(三)--RAC工作原理和相关组件

RAC 工作原理和相关组件 OracleRAC 是多个单实例在配置意义上的扩展&#xff0c;实现由两个或者多个节点&#xff08;实例&#xff09;使用一个共同的共享数据库&#xff08;例如&#xff0c;一个数据库同时安装多个实例并打开&#xff09;。在这种情况下&#xff0c;每一个单独…

【gulp+jq+html】添加环境变量,并在js中使用(判断环境,更改api接口域名)+ 附gulpfile.js代码

参考博文&#xff1a; gulp分离环境 gulp中如何配置环境变量 gulp环境变量配置 1、安装cross-env插件 npm install cross-env -d2、package.json更改scripts "scripts": {"clean": "gulp clean","serve:test": "cross-env NODE…

如何在Windows部署GoLand并通过SSH远程连接Linux服务器

文章目录 1. 安装配置GoLand2. 服务器开启SSH服务3. GoLand本地服务器远程连接测试4. 安装cpolar内网穿透远程访问服务器端4.1 服务器端安装cpolar4.2 创建远程连接公网地址 5. 使用固定TCP地址远程开发 本文主要介绍使用GoLand通过SSH远程连接服务器&#xff0c;并结合cpolar内…

python求解中位数

首先将数组nums进行排序&#xff0c;然后找到中间位置的数值 如果数组长度n为奇数&#xff0c;则(n1)/2处对应值为中位数&#xff0c;如果数组下标从0开始&#xff0c;还需要减去1 如果数组长度n为偶数&#xff0c;则n/2,n/21两个位置数的平均值为中位数 假设中位数为x&#x…

《计算机网络简易速速上手小册》第7章:云计算与网络服务(2024 最新版)

文章目录 7.1 云服务模型&#xff08;IaaS, PaaS, SaaS&#xff09;- 你的技术魔法盒7.1.1 基础知识7.1.2 重点案例&#xff1a;构建和部署 Python Web 应用实现步骤具体操作步骤1&#xff1a;创建 Flask Web 应用步骤2&#xff1a;准备应用部署 7.1.3 拓展案例1&#xff1a;使…