更新
wangEditor V5 已正式发布,查看官网。
前言
本文使用 wangEditor V5 实现 Vue2.6 编辑器。wangEditor V5 官方提供 Vue 组件,使用非常简单。
Vue3 的可参考 50 行代码 Vue3 使用富文本编辑器。
wangEditor V5 正在公开测试中,有问题和建议可以提交到 github issue 。
【注意】编辑器后续可能继续升级,API 和配置或许会调整。所以问题请及时查阅文档,不要仅依赖本文。
安装
使用 vue-cli 初始化一个 Vue2.6 环境,然后安装
yarn add @wangeditor/editor @wangeditor/editor-for-vue
注意
- 用于 Vue2 安装
@wangeditor/editor-for-vue
- 用于 Vue3 安装
@wangeditor/editor-for-vue@next
创建编辑器
写代码
创建一个 Vue 组件 MyEditor.vue
,代码约 50 行,逻辑也比较清晰 (源码在文章最后)
<template>
<div style="border: 1px solid #ccc;">
<!-- 工具栏 -->
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editor"
:defaultConfig="toolbarConfig"
/>
<!-- 编辑器 -->
<Editor
style="height: 500px; overflow-y: hidden;"
:defaultConfig="editorConfig"
v-model="html"
@onCreated="onCreated"
/>
</div>
</template>
<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
name: 'MyEditor',
components: { Editor, Toolbar },
data() {
return {
editor: null,
html: '<p>hello world</p>',
toolbarConfig: {},
editorConfig: {
placeholder: '请输入内容...',
}
}
},
methods: {
onCreated(editor) {
this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
},
},
mounted() {
// 模拟 ajax 请求,异步渲染编辑器
setTimeout(() => {
this.html = '<p>Ajax 异步设置内容 HTML</p>'
}, 1500)
},
beforeDestroy() {
const editor = this.editor
if (editor == null) return
editor.destroy() // 组件销毁时,及时销毁 editor ,重要!!!
},
}
</script>
<!-- 记得引入 wangEditor css 文件,重要 !!! -->
<style src="@wangeditor/editor/dist/css/style.css"></style>
运行
把 MyEditor.vue
引入到 App.vue
中,即可生成一个功能齐全的编辑器。
内容变化时 html
也会实时变化,即 html
中就是编辑器的最新内容。
注意事项
- 赋值
this.editor
时要使用Object.seal()
,否则会报错 - Vue 组件销毁时,及时销毁编辑器
配置
编辑器配置
上文代码中只配置了 placeholder
作为示例。它还支持 readOnly
autoFocus
maxLength
等配置,可参考文档。
editorConfig: {
placeholder: '请输入内容...',
// 继续其他配置...
},
但请注意,该文档中的所有回调函数,都不能以配置的形式传入,如 onCreated
onChange
onDestroyed
等。这些回调函数必须以 Vue 事件的方式传入。
<Editor
:editorId="editorId"
:defaultConfig="editorConfig"
:defaultContent="defaultContent"
:defaultHtml="defaultHtml"
<!-- 回调函数,以 Vue 事件形式 -->
@onCreated="onCreated"
@onChange="onChange"
@onDestroyed="onDestroyed"
@onMaxLength="onMaxLength"
@onFocus="onFocus"
@onBlur="onBlur"
@customAlert="customAlert"
@customPaste="customPaste"
/>
工具栏配置
如果你想修改工具栏的菜单,如隐藏某些菜单,重新排序分组,就可以使用该配置。支持 toolbarKeys
和 excludeKeys
,可参考文档。
toolbarConfig: {
toolbarKeys: [ /* 显示哪些菜单,如何排序、分组 */ ],
excludeKeys: [ /* 隐藏哪些菜单 */ ],
},
菜单配置
如果你想对某个菜单进行配置,例如配置颜色、字体、字号,配置上传图片的 API 地址等,可以使用菜单配置。具体参考文档。
editorConfig: {
placeholder: '请输入内容...',
// 所有的菜单配置,都要在 MENU_CONF 属性下
MENU_CONF: {
// 配置字号
fontSize: [ ... ],
// 配置上传图片
uploadImage: { ... },
// 继续其他菜单配置...
}
},
API
wangEditor 提供了丰富的 API ,可以帮助你进行任何编辑器操作。可参考文档。
- 配置相关的 API
- 内容处理相关的 API
- 节点操作相关的 API
- 选区操作相关的 API
- 自定义事件的 API
在编辑器创建完成之后,可以通过 this.editor
获取 editor
实例,然后执行 API 。
methods: {
// 点击一个 button 执行该函数
getEditorText() {
const editor = this.editor
if (editor == null) return
editor.getText() // 执行 editor API
}
},
总结
本文所有源代码在这里。
wangEditor V5 正在公开测试中,有问题和建议可以提交到 github issue 。