Alpine
以下指南描述了如何将 Tiptap 与版本 3 的 Alpine.js 集成。为了方便本指南,我们将使用 Vite 快速设置一个项目,但您可以使用您习惯的任何工具。Vite 真的很快,我们喜欢它!
要求
创建项目(可选)
如果您已经有一个 Alpine.js 项目,那也没关系。请跳过此步骤。
为了本指南的目的,从一个新的 Vite 项目开始,名为 my-tiptap-project。Vite 设置我们所需的一切,只需选择 Vanilla JavaScript 模板。
npm init vite@latest my-tiptap-project -- --template vanilla
cd my-tiptap-project
npm install
npm 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 的响应引擎会自动将组件属性包装在代理对象中。如果您尝试使用代理编辑器实例应用事务,将导致“范围错误:应用不匹配的事务”,因此请确保使用 Alpine.raw() 解包,或简单地避免将编辑器存储为组件属性,如本示例所示。
return {
updatedAt: Date.now(), // 强制 Alpine 在选择更改时重新渲染
init() {
const _this = this
editor = 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 = Alpine
Alpine.start()将其添加到您的应用程序
现在,让我们用以下示例代码替换 index.html 的内容,以在我们的应用程序中使用编辑器。
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
</head>
<body>
<div x-data="editor('<p>你好,世界!:-)</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) }">
粗体
</button>
<button @click="toggleItalic()" :class="{ 'is-active' : isActive('italic', updatedAt) }">
斜体
</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 应该在您的浏览器中可见。是时候给自己一个拥抱了!:)