最近开发新项目中使用到了富文本框,为了找一个简洁好用的富文本还真是不容易,特此给自己记录一下,也分享给大家!希望你需要的时候可以一步到位不用绕弯路。
网上常见的一些 tinymce-vue、quill、UEditor kindEditor ,国外的 CKEditor TinyMCE Quill ProseMirror Draft Slate 等等。我使用的是
wangeditor
编辑器。使用简单,界面简洁大气,功能齐全,菜单工具栏可编辑,是一款非常强大的编辑器,所以我选择了它。

一、wangEditor 优势
- 官方封装了 Vue React 组件,可以很方便的用于 Vue React 等框架。支持 vue2 和 vue3 。
- wangEditor 有详细的中文文档,以及中文交流环境。因为作者open in new window就是国内程序员。
- 使用 vdom 技术(基于snabbdom.jsopen in new window )做视图更新,model 和 view 分离,增加稳定性。
- 可以支持 TypeScript。
- 官方中文文档:https://www.wangeditor.com/v5/installation.html
二、针对 vue3 的安装及使用
安装:
yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save
yarn add @wangeditor/editor-for-vue@next
# 或者 npm install @wangeditor/editor-for-vue@next --save
使用
<template>
<div style="border: 1px solid #ccc">
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editorRef"
:defaultConfig="toolbarConfig"
:mode="mode"
/>
<Editor
style="height: 500px; overflow-y: hidden;"
v-model="valueHtml"
:defaultConfig="editorConfig"
:mode="mode"
@onCreated="handleCreated"
/>
</div>
</template>
<script>import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
components: { Editor, Toolbar },
setup() {
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('<p>hello</p>')
// 模拟 ajax 异步获取内容
onMounted(() => {
setTimeout(() => {
valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
}, 1500)
})
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value
if (editor == null) return
editor.destroy()
})
const handleCreated = (editor) => {
editorRef.value = editor // 记录 editor 实例,重要!
}
return {
editorRef,
valueHtml,
mode: 'default', // 或 'simple'
toolbarConfig,
editorConfig,
handleCreated
};
}
}
</script>
三、个性化配置
- 工具栏配置 - 插入新菜单,屏蔽某个菜单等
- 编辑器配置 - 兼听各个生命周期,自定义粘贴
- 菜单配置 - 配置颜色、字体、字号、链接校验、上传图片、视频等
注意:配置项写的时候有 JS 和 TS 两种写法,参考官方文档配置:https://www.wangeditor.com/v5/toolbar-config.html。