基于 Vue 的Tiptap 富文本编辑器使用指南

目录

🧰 技术栈

📦 所需依赖

📁 文件结构

🧱 编辑器组件实现(components/Editor.vue)

✨ 常用操作指令

🧠 小贴士

🧩 Tiptap 扩展功能使用说明(含快捷键与命令)

🔹 StarterKit(基础功能集)

🔹 Link(链接)

🔹 Table(表格)

🔹 CodeBlockLowlight(代码块 + 语法高亮)

🔹 Placeholder(占位提示)

🔹 Image(图片上传)

🔹 自定义 Attachment(附件上传)

tiptap collaborative 实时协作

网络实时通信

WebSocket 推荐

WebSocket 后端

多个服务器

显示光标

离线支持

🔗 推荐链接

✅ 总结


本文是针对零基础前端开发者撰写,目的是快速上手并集成一个功能完整的富文本编辑器(Tiptap)到你的 Vue 项目中。


🧰 技术栈

  • Vue 3 + <script setup>

  • Tiptap(基于 ProseMirror)

  • 多种 Tiptap 插件(Extension)支持


📦 所需依赖

npm install @tiptap/vue-3 @tiptap/starter-kit \@tiptap/extension-link \@tiptap/extension-table \@tiptap/extension-table-row \@tiptap/extension-table-cell \@tiptap/extension-table-header \@tiptap/extension-placeholder \@tiptap/extension-code-block-lowlight \@tiptap/extension-image \@tiptap/extension-character-count \lowlight

📁 文件结构

src/
├─ components/
│  └─ Editor.vue    # 编辑器组件
└─ App.vue

🧱 编辑器组件实现(components/Editor.vue)

<template><editor-content :editor="editor" class="editor" />
</template><script setup>
import { onBeforeUnmount } from 'vue'
import { Editor, EditorContent } from '@tiptap/vue-3'import StarterKit from '@tiptap/starter-kit'
import Link from '@tiptap/extension-link'
import Table from '@tiptap/extension-table'
import TableRow from '@tiptap/extension-table-row'
import TableCell from '@tiptap/extension-table-cell'
import TableHeader from '@tiptap/extension-table-header'
import Placeholder from '@tiptap/extension-placeholder'
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'
import { lowlight } from 'lowlight/lib/common'
import Image from '@tiptap/extension-image'
import CharacterCount from '@tiptap/extension-character-count'const editor = new Editor({extensions: [StarterKit,Link,Placeholder.configure({ placeholder: '请输入内容…' }),Table.configure({ resizable: true }),TableRow,TableCell,TableHeader,CodeBlockLowlight.configure({ lowlight }),Image,CharacterCount.configure({ limit: 500 }),],content: '<p>Hello Tiptap!</p>',
})onBeforeUnmount(() => {editor.destroy()
})
</script><style scoped>
.editor {border: 1px solid #ccc;padding: 16px;border-radius: 8px;min-height: 200px;
}
</style>

✨ 常用操作指令

  • 获取 HTML 内容:

editor.getHTML()
  • 获取 JSON 内容:

editor.getJSON()
  • 执行命令示例(如设置为加粗):

editor.commands.toggleBold()

🧠 小贴士

  • 所有 Extension 都可以配置和拓展,官方文档中提供了详细 API。

  • 菜单栏需要你自行实现,可以通过组合 editor.commands 来制作按钮。

  • 可自定义 CSS 样式,支持暗色模式、响应式布局等。


🧩 Tiptap 扩展功能使用说明(含快捷键与命令)

以下内容将详细列出各个 Tiptap 扩展的使用方式,包括:

  • 如何引入

  • 如何注册(放进 extensions)

  • 快捷键(如有)

  • 使用 editor.commands 如何触发


🔹 StarterKit(基础功能集)

  • 引入

import StarterKit from '@tiptap/starter-kit'
  • 注册

extensions: [ StarterKit ]
  • 快捷键(默认):

    • 加粗:Mod-b

    • 斜体:Mod-i

    • 标题:Ctrl-Alt-1~6

    • 列表:Shift-Ctrl-8/9

  • 命令示例

editor.commands.toggleBold()
editor.commands.toggleItalic()
editor.commands.toggleHeading({ level: 2 })
editor.commands.toggleBulletList()

🔹 Link(链接)

  • 引入

import Link from '@tiptap/extension-link'
  • 注册

extensions: [ Link.configure({ openOnClick: true }) ]
  • 快捷键:无默认

  • 命令示例

editor.commands.setLink({ href: 'https://example.com' })
editor.commands.unsetLink()

🔹 Table(表格)

  • 引入

import Table from '@tiptap/extension-table'
import TableRow from '@tiptap/extension-table-row'
import TableHeader from '@tiptap/extension-table-header'
import TableCell from '@tiptap/extension-table-cell'
  • 注册

extensions: [Table.configure({ resizable: true }),TableRow,TableHeader,TableCell,
]
  • 快捷键:无默认

  • 命令示例

editor.commands.insertTable({ rows: 3, cols: 3 })
editor.commands.addColumnAfter()
editor.commands.deleteTable()

🔹 CodeBlockLowlight(代码块 + 语法高亮)

  • 引入

import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'
import { lowlight } from 'lowlight/lib/common'
  • 注册

extensions: [CodeBlockLowlight.configure({ lowlight }),
]
  • 快捷键

    • `Ctrl + Shift + ``

  • 命令示例

editor.commands.toggleCodeBlock()

🔹 Placeholder(占位提示)

  • 引入

import Placeholder from '@tiptap/extension-placeholder'
  • 注册

extensions: [Placeholder.configure({ placeholder: '请输入内容…' })
]
  • 快捷键:无

  • 命令示例:无,主要是展示效果


🔹 Image(图片上传)

  • 引入

import Image from '@tiptap/extension-image'
  • 注册

extensions: [ Image ]
  • 快捷键:无

  • 命令示例

editor.commands.setImage({ src: 'https://example.com/image.jpg' })

通常结合 <input type="file"> 使用,将图片上传到服务器后获取链接插入。


🔹 自定义 Attachment(附件上传)

Tiptap 没有内建“附件”类型,可自定义扩展:

  • 引入(自定义 Node):

async handleFileUpload(e) {const file = e.target.files[0];if (!file) return;try {// 1. 上传文件到服务器(假设 uploadImage 支持所有类型或调整为通用上传函数)const url = await this.uploadImage(file);// 2. 根据文件类型插入内容if (file.type.startsWith('image/')) {// 插入图片this.editor.chain().focus().setImage({ src: url }).run();} else {// 非图片类型插入“附件”文本(可带链接)this.editor.chain().focus().insertContent('附件').run();// 如需插入链接:this.editor.chain().focus().insertContent(`<a href="${url}">附件</a>`).run();}} catch (error) {console.error("上传失败:", error);alert("上传失败,请重试");} finally {e.target.value = null;}
}
    • 快捷键:无

    • 命令示例

    editor.commands.insertContent({type: 'attachment',attrs: {href: 'https://example.com/file.pdf',filename: '报告文件.pdf',},
    })

    上传方式与图片类似,使用 file input 或拖拽上传后插入链接。


    tiptap collaborative 实时协作

    tiptap 支持实时协作、让不同设备之间的同步和离线工作。通过与 Y.js 配合使用无需多少代码即可实现多人在线实时协作,不过在大部分的实践工作中,实时协作并不是一个强需求。

    网络实时通信

    WebRTC仅使用服务器让各个客户端(浏览器)击行相互通讯。服务器并不参与数据的传输。
    安装依赖项:

    npm install @tiptap/extension-collaboration yjs y-webrtc y-prosemirror

    然后创建一个 Y 文档,并注册到 Tiptap:

    import { WebrtcProvider } from 'y-webrtc'// A new Y document
    const ydoc = new Y.Doc()
    // Registered with a WebRTC provider
    const provider = new WebrtcProvider('example-document', ydoc)const editor = new Editor({extensions: [StarterKit.configure({// The Collaboration extension comes with its own history handlinghistory: false,}),// Register the document with TiptapCollaboration.configure({document: ydoc,}),],
    })

    到此为止你就可以让不同的用户进行实时协作了,它是如何运行的呢?WebRTC程序通过公共服务器将客户端连接在一起,服务器并不同步实际的更改,然而这个也有两个缺点。
    1,浏览器拒绝连接太多客户端,对于同一文档中超过 100+ 个并发客户端,它不能很好的支持。
    2,服务器没有参与文档记录的更改,因为WebRTC信令服务器不会收到更改,因此不知道文档中的内容。
    如果你想更深入地研究,请前往GitHub上的Y WebRTC存储库

    WebSocket 推荐

    对于大多数情况,tiptap建议使用 WebSocket ,因为它更灵活,也可以很好地扩展。为了更容易使用,tiptap发布了Hocuspocus作为Tiptap的官方后端程序。

    对于客户端示例几乎相同,只不过驱动程序不同。首先,让我们安装依赖项:

    npm install @tiptap/extension-collaboration @hocuspocus/provider y-prosemirror

    然后向 Tiptap 注册 WebSocket 供应程序:

    import { Editor } from '@tiptap/core'
    import StarterKit from '@tiptap/starter-kit'
    import Collaboration from '@tiptap/extension-collaboration'
    import { HocuspocusProvider } from '@hocuspocus/provider'// Set up the Hocuspocus WebSocket provider
    const provider = new HocuspocusProvider({url: 'ws://127.0.0.1:1234',name: 'example-document',
    })const editor = new Editor({extensions: [StarterKit.configure({// The Collaboration extension comes with its own history handlinghistory: false,}),// Register the document with TiptapCollaboration.configure({document: provider.document,}),],
    })

    如你所见此示例不是开箱即用的。它需要配置为与WebSocket服务器通信,因此需要安装WebSocket 后端程序Hocuspocus。

    WebSocket 后端

    为了使服务器部分尽可能简单,tiptap提供了一个node.js的服务器包 Hocuspocus。它是一个灵活的 Node.js 包,可用于构建后端。
    下面的命令用来启动这个服务:

    npx @hocuspocus/cli --port 1234 --sqlite

    运行 Hocuspocus 命令行,启动侦听1234端口并将更改存储在内存中(一旦停止命令,它就会消失),输出如下所示:

    Hocuspocus v1.0.0 running at:> HTTP: http://127.0.0.1:1234
    > WebSocket: ws://127.0.0.1:1234Ready.

    尝试在浏览器中打开 http://127.0.0.1:1234 网址,如果一切运行正常,你应该会看到一个纯文本。
    然后返回 Tiptap 编辑器并F5刷新网页,它将连接到 Hocuspocus WebSocket 服务器,这时就可以与其他用户进行实时协作了。

    多个服务器

    你可以注册多个服务器保证服务的稳定,当一个服务器宕机客户端将连接另外一个服务器

    new WebrtcProvider('example-document', ydoc)
    new HocuspocusProvider({url: 'ws://127.0.0.1:1234',name: 'example-document',document: ydoc,
    })

    显示光标

    当多个人进行在线编辑,你可以设置每个人的昵称显示在编辑器光标位置

    import { Editor } from '@tiptap/core'
    import StarterKit from '@tiptap/starter-kit'
    import Collaboration from '@tiptap/extension-collaboration'
    import CollaborationCursor from '@tiptap/extension-collaboration-cursor'
    import { HocuspocusProvider } from '@hocuspocus/provider'// Set up the Hocuspocus WebSocket provider
    const provider = new HocuspocusProvider({url: 'ws://127.0.0.1:1234',name: 'example-document',
    })const editor = new Editor({extensions: [StarterKit.configure({// The Collaboration extension comes with its own history handlinghistory: false,}),Collaboration.configure({document: provider.document,}),// Register the collaboration cursor extensionCollaborationCursor.configure({provider: provider,user: {name: 'Cyndi Lauper',color: '#f783ac',},}),],
    })

    离线支持

    基于Y IndexedDB 你可以实现关闭浏览器后所有更改都将存储在浏览器中,下次联机时,WebSocket 提供程序将尝试查找连接并最终同步更改。

    如需添加更多扩展(如任务列表、缩进、emoji 等),可以继续在此格式基础上扩展。

    🔗 推荐链接

    • tiptap 自定义扩展 | 抠丁客
    • 官方网站:Tiptap - Dev Toolkit Editor Suite

    • GitHub:https://github.com/ueberdosis/tiptap

    • ProseMirror 引擎:ProseMirror

    ✅ 总结

    本文总结了一个基于 Vue3 + Tiptap 的富文本编辑器完整实现过程,涵盖依赖安装、扩展配置、编辑器初始化与常用操作,适合新手开发者快速上手。如果你希望快速搭建一个功能完整的编辑器,完全可以直接复制本文结构并根据需求调整内容。

    本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/77805.shtml

    如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

    相关文章

    统计图表ECharts

    统计某个时间段&#xff0c;观看人数 ①、数据表 ②、业务代码 RestController RequstMapping(value"/admin/vod/videoVisitor") CrossOrigin public class VideoVisitorController{Autowriedprivate VideoVisitorService videoVisitorService;//课程统计的接口…

    ubuntu 安装 redis server

    ubuntu 安装 redis server sudo apt update sudo apt install redis-server The following NEW packages will be installed:libhiredis0.14 libjemalloc2 liblua5.1-0 lua-bitop lua-cjson redis-server redis-toolssudo systemctl start redis-server sudo systemctl ena…

    【白雪讲堂】[特殊字符]内容战略地图|GEO优化框架下的内容全景布局

    &#x1f4cd;内容战略地图&#xff5c;GEO优化框架下的内容全景布局 1️⃣ 顶层目标&#xff1a;GEO优化战略 目标关键词&#xff1a; 被AI理解&#xff08;AEO&#xff09; 被AI优先推荐&#xff08;GEO&#xff09; 在关键场景中被AI复读引用 2️⃣ 三大引擎逻辑&#x…

    NVIDIA 自动驾驶技术见解

    前言 参与 NVIDIA自动驾驶开发者实验室 活动&#xff0c;以及解读了 NVIDIA 安全报告 自动驾驶 白皮书&#xff0c;本文是我的一些思考和见解。自动驾驶技术的目标是为了改善道理安全、减少交通堵塞&#xff0c;重塑更安全、高效、包容的交通生态。在这一领域&#xff0c;NVI…

    OpenCV day6

    函数内容接上文&#xff1a;OpenCV day4-CSDN博客 , OpenCV day5-CSDN博客 目录 平滑&#xff08;模糊&#xff09; 25.cv2.blur()&#xff1a; 26.cv2.boxFilter(): 27.cv2.GaussianBlur()&#xff1a; 28.cv2.medianBlur(): 29.cv2.bilateralFilter()&#xff1a; 锐…

    Function calling, 模态上下文协议(MCP),多步能力协议(MCP) 和 A2A的区别

    背景阐述 本文大部分内容都是基于openAI 的 chatGPT自动生成。作者进行了一些细微的调整。 LLM 带来了很多思维的活跃&#xff0c;基于LLM&#xff0c;产生了很多应用&#xff0c;很多应用也激活了LLM的新的功能。 Function calling&#xff0c;MCP&#xff08;Modal Contex…

    火山RTC 5 转推CDN 布局合成规则

    实时音视频房间&#xff0c;转推CDN&#xff0c;文档&#xff1a; 转推直播--实时音视频-火山引擎 一、转推CDN 0、前提 * 在调用该接口前&#xff0c;你需要在[控制台](https://console.volcengine.com/rtc/workplaceRTC)开启转推直播功能。<br> * 调…

    力扣面试150题--插入区间和用最少数量的箭引爆气球

    Day 28 题目描述 思路 初次思路&#xff1a;借鉴一下昨天题解的思路&#xff0c;将插入的区间与区间数组作比较&#xff0c;插入到升序的数组中&#xff0c;其他的和&#xff08;合并区间&#xff09;做法一样。 注意需要特殊处理一下情况&#xff0c;插入区间比数组中最后一…

    【Java面试笔记:基础】4.强引用、软引用、弱引用、幻象引用有什么区别?

    1. 引用类型及其特点 强引用(Strong Reference): 定义:最常见的引用类型,通过new关键字直接创建。回收条件:只要强引用存在,对象不会被GC回收。示例:Object obj = new Object(); // 强引用特点: 强引用是导致内存泄漏的常见原因(如未及时置为null)。手动断开引用:…

    ycsb性能测试的优缺点

    YCSB&#xff08;Yahoo Cloud Serving Benchmark&#xff09;是一个开源的性能测试框架&#xff0c;用于评估分布式系统的读写性能。它具有以下优点和缺点&#xff1a; 优点&#xff1a; 简单易用&#xff1a;YCSB提供了简单的API和配置文件&#xff0c;使得性能测试非常容易…

    基于SpringBoot的校园赛事直播管理系统-项目分享

    基于SpringBoot的校园赛事直播管理系统-项目分享 项目介绍项目摘要管理员功能图用户功能图项目预览首页总览个人中心礼物管理主播管理 最后 项目介绍 使用者&#xff1a;管理员、用户 开发技术&#xff1a;MySQLJavaSpringBootVue 项目摘要 随着互联网和移动技术的持续进步&…

    Nginx​中间件的解析

    目录 一、Nginx的核心架构解析 二、Nginx的典型应用场景 三、Nginx的配置优化实践 四、Nginx的常见缺陷与漏洞 一、Nginx的核心架构解析 ​​事件驱动与非阻塞IO模型​​ Nginx采用基于epoll/kq等系统调用的事件驱动机制&#xff0c;通过异步非阻塞方式处理请求&#xff0c;…

    杭州小红书代运营公司-品融电商:全域增长策略的实践者

    杭州小红书代运营公司-品融电商&#xff1a;全域增长策略的实践者 在品牌竞争日趋激烈的电商领域&#xff0c;杭州品融电商作为一家专注于品牌化全域运营的服务商&#xff0c;凭借其“效品合一”方法论与行业领先的小红书代运营能力&#xff0c;已成为众多品牌实现市场突围的重…

    【映客直播-注册/登录安全分析报告】

    前言 由于网站注册入口容易被黑客攻击&#xff0c;存在如下安全问题&#xff1a; 暴力破解密码&#xff0c;造成用户信息泄露短信盗刷的安全问题&#xff0c;影响业务及导致用户投诉带来经济损失&#xff0c;尤其是后付费客户&#xff0c;风险巨大&#xff0c;造成亏损无底洞…

    Android audio_policy_configuration.xml加载流程

    目录 一、audio_policy_configuration.xml文件被加载流程 1、AudioPolicyService 创建阶段 2、createAudioPolicyManager 实现 3、AudioPolicyManager 构造 4、配置文件解析 loadConfig 5、核心解析逻辑 PolicySerializer::deserialize 二、AudioPolicyConfig类解析 1、…

    使用 Docker 安装 Elastic Stack 并重置本地密码

    Elastic Stack&#xff08;也被称为 ELK Stack&#xff09;是一个非常强大的工具套件&#xff0c;用于实时搜索、分析和可视化大量数据。Elastic Stack 包括 Elasticsearch、Logstash、Kibana 等组件。本文将展示如何使用 Docker 安装 Elasticsearch 并重置本地用户密码。 ###…

    Unitest和pytest使用方法

    unittest 是 Python 自带的单元测试框架&#xff0c;用于编写和运行可重复的测试用例。它的核心思想是通过断言&#xff08;assertions&#xff09;验证代码的行为是否符合预期。以下是 unittest 的基本使用方法&#xff1a; 1. 基本结构 1.1 创建测试类 继承 unittest.TestC…

    git 版本提交规范

    Git 提交规范&#xff08;Git Commit Message Convention&#xff09;是为了让项目的提交历史更加清晰、可读、便于追踪和自动化工具解析。常见的规范之一是 Conventional Commits&#xff0c;下面是一个推荐的格式规范&#xff1a; &#x1f31f; 提交信息格式&#xff08;Con…

    stat判断路径

    int stat(const char *pathname, struct stat *buf); pathname&#xff1a;用于指定一个需要查看属性的文件路径。 buf&#xff1a;struct stat 类型指针&#xff0c;用于指向一个 struct stat 结构体变量。调用 stat 函数的时候需要传入一个 struct stat 变量的指针&#xff0…

    学习Docker遇到的问题

    目录 1、拉取hello-world镜像报错 1. 检查网络连接 排查: 2. 配置 Docker 镜像加速器(推荐) 具体解决步骤: 1.在服务器上创建并修改配置文件,添加Docker镜像加速器地址: 2. 重启Docker 3. 拉取hello-world镜像 2、删除镜像出现异常 3、 容器内部不能运行ping命令 …