Alpine.js 集成 tiptap
引言
本指南将指导您如何在 Alpine.js 3.x 版本中集成 Tiptap。我们将使用 Vite 快速搭建项目,但您可以根据自己的喜好选择任何工具。Vite 速度非常快,我们很喜欢。
需要的条件
1. 创建项目(可选)
如果您已有现有的 Alpine.js 项目,那也很好。跳过此步骤,直接进行下一步。
为了演示,我们从一个名为 my-tiptap-project
的新 Vite 项目开始。Vite 会为我们设置好一切,选择 Vanilla JavaScript 模板即可。
npm init vite@latest my-tiptap-project -- --template vanilla
cd my-tiptap-project
npm install
npm run dev
2. 安装依赖
好了,无聊的初始化工作到此为止。现在让我们安装 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 。如果您在现有项目中工作,可能会有所不同。
3. 初始化编辑器
要开始使用 Tiptap,我们需要编写一些 JavaScript。请将以下代码放入名为 main.js
的文件中。
这是使用 Alpine.js 快速启动 Tiptap 的最快方法。它为您提供了一个基础版的 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().toggleBold().focus().run();
},
toggleItalic() {
editor.chain().toggleItalic().focus().run();
},
};
});
});
window.Alpine = Alpine;
Alpine.start();
4. 将其添加到您的应用中
现在,让我们用以下示例代码替换 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 了。给自己点个赞吧! :)