Vue3 + TS + Vite 项目引入富文本框
最近开发新项目中使用到了富文本框,为了找一个简洁好用的富文本还真是不容易,特此给自己记录一下,也分享给大家!希望你需要的时候可以一步到位不用绕弯路。
网上常见的一些 tinymce-vue、quill、UEditor kindEditor ,国外的 CKEditor TinyMCE Quill ProseMirror Draft Slate 等等。我使用的是 wangeditor
编辑器。使用简单,界面简洁大气,功能齐全,菜单工具栏可编辑,是一款非常强大的编辑器,所以我选择了它。
一、wangEditor 优势
- 官方封装了 Vue React 组件,可以很方便的用于 Vue React 等框架。支持 vue2 和 vue3 。
- wangEditor 有详细的中文文档,以及中文交流环境。因为作者就是国内程序员。
- 使用 vdom 技术(基于 snabbdom.js )做视图更新,model 和 view 分离,增加稳定性。
- 可以支持 TypeScript。
- 官方中文文档:https://www.wangeditor.com/v5/installation.html
二、针对 vue3 的安装及使用
安装:
1 2 3 4 5 | yarn add @wangeditor/editor # 或者 npm install @wangeditor/editor --save yarn add @wangeditor/editor- for -vue@next # 或者 npm install @wangeditor/editor-for-vue@next --save |
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | <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。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?