以下指南描述了如何将 Tiptap 集成到 Alpine.js 版本 3 中。为了方便演示,我们将使用 Vite 来快速设置项目,但你也可以使用你熟悉的任何工具。Vite 真的非常快,我们非常喜欢它!
要求
创建项目(可选)
如果你已经有一个 Alpine.js 项目,那也没问题,可以跳过此步骤。
在本指南中,我们将从头开始创建一个新的 Vite 项目,命名为 my-tiptap-project。Vite 设置了我们所需的一切,只需选择 Vanilla JavaScript 模板即可。
npm init vite@latest my-tiptap-project -- --template vanillacd my-tiptap-projectnpm installnpm run dev
安装依赖
好了,模板项目已经准备好,接下来让我们安装 Tiptap!在这个示例中,你需要安装 alpinejs,@tiptap/core 包,@tiptap/pm 包,以及 @tiptap/starter-kit,它包含了大多数常见的扩展,可以帮助你快速上手。
npm install alpinejs @tiptap/core @tiptap/pm @tiptap/starter-kit
如果你完成了步骤 1,你可以通过运行 npm run dev 启动项目,并在浏览器中打开 http://localhost:5173。如果你是在现有项目中操作,端口号可能会有所不同。
集成 Tiptap
要开始使用 Tiptap,你需要写一点 JavaScript。我们将以下示例代码放入名为 main.js 的文件中。
这是将 Tiptap 与 Alpine.js 配合使用的最快方式。它将为你提供一个非常基本的 Tiptap 版本。不用担心,稍后你可以添加更多功能。
import Alpine from 'alpinejs'import { Editor } from '@tiptap/core'import StarterKit from '@tiptap/starter-kit'document.addEventListener('alpine:init', () => {Alpine.data('editor', (content) => {let editor // Alpine 的响应式引擎会自动将组件属性包装在代理对象中。如果你尝试使用代理的 editor 实例来应用事务,它将导致 "Range Error: Applying a mismatched transaction" 错误。因此,确保使用 Alpine.raw() 来解包它,或者像本示例中那样避免将 editor 存储为组件属性。return {updatedAt: Date.now(), // 强制 Alpine 在选择发生变化时重新渲染init() {const _this = thiseditor = new Editor({element: this.$refs.element,extensions: [StarterKit],content: content,onCreate({ editor }) {_this.updatedAt = Date.now()},onUpdate({ editor }) {_this.updatedAt = Date.now()},onSelectionUpdate({ editor }) {_this.updatedAt = Date.now()},})},isLoaded() {return editor},isActive(type, opts = {}) {return editor.isActive(type, opts)},toggleHeading(opts) {editor.chain().toggleHeading(opts).focus().run()},toggleBold() {editor.chain().focus().toggleBold().run()},toggleItalic() {editor.chain().toggleItalic().focus().run()},}})})window.Alpine = AlpineAlpine.start()
将其添加到你的应用
现在,替换 index.html 文件的内容,并使用编辑器组件:
<!doctype html><html lang="en"><head><meta charset="UTF-8" /></head><body><div x-data="editor('<p>Hello world! :-)</p>')"><template x-if="isLoaded()"><div class="menu"><button@click="toggleHeading({ level: 1 })":class="{ 'is-active': isActive('heading', { level: 1 }, updatedAt) }">H1</button><button @click="toggleBold()" :class="{ 'is-active' : isActive('bold', updatedAt) }">Bold</button><button @click="toggleItalic()" :class="{ 'is-active' : isActive('italic', updatedAt) }">Italic</button></div></template><div x-ref="element"></div></div><script type="module" src="/main.js"></script><style>body {margin: 2rem;font-family: sans-serif;}button.is-active {background: black;color: white;}.tiptap {padding: 0.5rem 1rem;margin: 1rem 0;border: 1px solid #ccc;}</style></body></html>
Tiptap 现在应该可以在浏览器中看到啦。给自己点个赞吧!:)
