wangEditor V5 精简完整参考手册

官网:www.wangeditor.com/v5/ 【V5 已经停止新增功能,仅可继续使用 】 底层基于 Slate,分为 编辑器实例 + 工具栏实例 两个独立对象

一、快速接入(原生JS)

1. 安装

sql 复制代码
npm install @wangeditor/editor --save

2. 最简Demo

xml 复制代码
<div id="toolbar-container"></div>
<div id="editor-container"></div>

<script type="module">
import '@wangeditor/editor/dist/css/style.css'
import { createEditor, createToolbar } from '@wangeditor/editor'

const editor = createEditor({
  selector: '#editor-container',
  html: '<p>初始内容</p>',
  config: {
    placeholder: '请输入内容...',
    onChange(editor) {
      console.log('html:', editor.getHtml())
      console.log('json:', editor.children)
    }
  }
})

const toolbar = createToolbar({
  editor,
  selector: '#toolbar-container',
  config: {
    // 工具栏菜单配置
  }
})
</script>

二、editor 配置(createEditor 的 config)

javascript 复制代码
editorConfig = {
  placeholder: '请输入',
  readOnly: false, // 只读
  autoFocus: true, // 自动聚焦
  maxLength: null, // 最大字符数
  // 生命周期
  onCreated(editor) {},    // 创建完成
  onChange(editor) {},     // 内容/选区变化
  onDestroyed(editor) {},  // 销毁
  onBlur(editor) {},
  onFocus(editor) {},

  // 粘贴
  pasteFilterStyle: true, // 过滤粘贴样式
  pasteIgnoreImg: false,  // 忽略粘贴图片

  // 图片上传
  MENU_CONF: {
    uploadImage: {
      server: '/api/upload',
      fieldName: 'file',
      maxFileSize: 2 * 1024 * 1024,
      allowedFileTypes: ['image/*'],
      // 自定义上传
      customUpload(file, insertFn) {
        // 上传成功后 insertFn(url, alt, href)
      }
    },
    // 视频上传 uploadVideo 同理
  },

  // 自定义菜单、hoverbar、弹窗
  hoverbarKeys: {},
  EXTEND_CONF: {}
}

三、toolbar 工具栏配置

arduino 复制代码
toolbarConfig = {
  toolbarKeys: [
    // 全部菜单 key
    'bold', 'underline', 'italic', 'strikeThrough',
    'color', 'bgColor', 'fontSize', 'fontFamily',
    'headerSelect', 'blockquote', 'codeBlock',
    'link', 'insertImage', 'insertVideo', 'insertTable',
    'divider', 'undo', 'redo', 'fullScreen', 'code',
  ],
  excludeKeys: [], // 排除不需要的菜单
  modalAppendToBody: true, // 弹窗挂载body
}

菜单key清单

文本样式:bold、italic、underline、strikeThrough、color、bgColor、fontSize、fontFamily

块级:headerSelect、header1、header2、blockquote、codeBlock、divider

插入:link、insertImage、insertVideo、insertTable

列表:bulletedList、numberedList

对齐:justifyLeft、justifyCenter、justifyRight、justifyJustify

其他:undo、redo、fullScreen、print、code

四、editor 实例 API(核心)

scss 复制代码
// -------- 内容读写 --------
editor.getHtml()                // 获取HTML字符串(存数据库用)
editor.getHtml({ format: true })
editor.getJson()                // 获取JSON结构(等价editor.children)
editor.getText()                // 获取纯文本
editor.setHtml('<p>xxx</p>')    // 设置HTML
editor.setContent([...json])    // 设置JSON内容

// -------- 选区 & 光标 --------
editor.focus()                  // 聚焦;focus(true) 光标跳到末尾
editor.blur()
editor.isFocused()              // true/false
editor.getSelection()           // 获取选区
editor.restoreSelection()
editor.saveSelection()

// -------- 插入内容 --------
editor.insertText('文字')
editor.insertHtml('<p>xxx</p>')
editor.insertNode({ type: 'paragraph', children: [{text: 'xxx'}] })

// -------- 禁用/只读 --------
editor.enable()
editor.disable()
editor.isDisabled()

// -------- 全屏 --------
editor.isFullScreen
editor.toggleFullScreen()

// -------- 销毁 --------
editor.destroy()

// -------- 上传进度 --------
editor.showProgressBar(0~100)
editor.hideProgressBar()

// -------- 滚动 --------
editor.scrollToElem(elemId)

⚠️ updateView() 内部API,不建议频繁调用

五、内容节点结构(JSON)

wangEditor 是 slate 节点树,不要自己随便拼HTML ,优先用 editor.getHtml() 保存:

yaml 复制代码
[
  {
    type: 'paragraph',
    children: [
      { text: '普通文字', bold: true, color: '#f00' }
    ]
  }
]

常用 type:paragraph、header1/header2...、blockquote、codeBlock、table、image、video、link

六、图片/视频上传(高频)

vbnet 复制代码
MENU_CONF: {
  uploadImage: {
    server: '/api/upload',
    // 后端返回格式必须:{ "errno":0, "data": { "url": "xxx" } }
    // 自定义上传(axios/fetch)
    customUpload: async (file, insertFn) => {
      const fd = new FormData()
      fd.append('file', file)
      const res = await fetch('/api/upload', {method:'POST', body:fd})
      const json = await res.json()
      insertFn(json.url, '图片alt', json.url)
    }
  }
}

七、Vue3 / React 官方组件

Vue3

xml 复制代码
<template>
  <div style="border:1px solid #ccc">
    <Toolbar :editor="editorRef" />
    <Editor v-model="valueHtml" :defaultConfig="editorConfig" @onCreated="handleCreated"/>
  </div>
</template>
<script setup>
import { ref, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

const editorRef = shallowRef()
const valueHtml = ref('<p>hello</p>')
const editorConfig = { placeholder: '请输入' }
const handleCreated = (editor) => { editorRef.value = editor }
</script>

Vue3 编辑器实例必须用 shallowRef

八、常见坑 & 注意事项

  1. HTML 兼容性限制 :只能识别 editor.getHtml() 输出的HTML,不支持任意外部HTML(比如 <span style="font-weight:bold"> 识别不了,只认 <strong>)
  2. 不要直接操作内部DOM,全部走 editor API
  3. 表单提交:存 getHtml(),不要存 JSON;JSON适合实时协作、二次编辑
  4. 销毁:弹窗/路由离开时一定要 editor.destroy(),否则内存泄漏
  5. 粘贴Word:默认会过滤大量样式,如需保留样式要调整 pasteFilterStyle

九、常用自定义扩展

  1. 自定义按钮/菜单:registerMenu
  2. 自定义元素(公式、附件、代码块增强):registerElement
  3. 自定义渲染、自定义hover悬浮菜单

十、官方文档导航页(原版完整手册)

相关推荐
用户298698530141 小时前
React 前端实现 Excel 与 CSV 互转:基于 WebAssembly 的浏览器端方案
javascript·react.js·excel
1-1=017 小时前
Vue 3 模板语
前端·javascript·vue.js
风卿17 小时前
看着AI写代码太孤独了,来欣赏星云吧:一个DSH 装饰插件
前端·javascript
牧艺17 小时前
弹层不用再手算坐标了:CSS Anchor Positioning 从原理到可上线
前端·javascript·css
愚坤18 小时前
前端真有意思,JS还能独立做项目?
前端·javascript·github
李纲明20 小时前
微信小程序 getSystemInfo 提示已废弃、屏幕高度算错胶囊还对不齐?getWindowInfo 和 getDeviceInfo 怎么接才稳
javascript·微信小程序·小程序·小程序开发·devdiy
FungLeo21 小时前
成为全栈·Vue 管理后台篇·用 fetch 建一层可控的请求内核
前端·javascript·vue.js·http·fetch·formdata·接口封装
用户842981424181021 小时前
ByteJS,让重要的 JavaScript 以字节码运行。
javascript
FungLeo1 天前
成为全栈·Vue 管理后台篇·Vue Router如何守住多角色后台边界
前端·javascript·vue.js·rbac·vue router·路由守卫·前端权限