Vue3 + TS + Vite 项目引入富文本框

最近开发新项目中使用到了富文本框,为了找一个简洁好用的富文本还真是不容易,特此给自己记录一下,也分享给大家!希望你需要的时候可以一步到位不用绕弯路。

网上常见的一些 tinymce-vue、quill、UEditor kindEditor ,国外的 CKEditor TinyMCE Quill ProseMirror Draft Slate 等等。我使用的是  wangeditor 编辑器。使用简单,界面简洁大气,功能齐全,菜单工具栏可编辑,是一款非常强大的编辑器,所以我选择了它。

一、wangEditor 优势

  1.  官方封装了 Vue React 组件,可以很方便的用于 Vue React 等框架。支持 vue2 和 vue3 。
  2. wangEditor 有详细的中文文档,以及中文交流环境。因为作者open in new window就是国内程序员。
  3. 使用 vdom 技术(基于 snabbdom.jsopen in new window )做视图更新,model 和 view 分离,增加稳定性。
  4. 可以支持 TypeScript。
  5. 官方中文文档: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。

  

posted @   前端人  阅读(1984)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示