你可以将 Tiptap 与 Laravel、Livewire、Inertia.js、Alpine.js、Tailwind CSS,甚至—是的,你没看错—在 PHP 中一起使用。
我们提供了 官方 PHP 包来处理 Tiptap 内容,你可以将 Tiptap 兼容的 JSON 转换为 HTML,反之亦然,清理内容,或者修改它。
Laravel Livewire
my-livewire-component.blade.php
<!--
在你的 Livewire 组件中,你可以添加一个
自动保存方法,用来每 10 秒保存一次编辑器的内容
-->
<x-editor wire:model="foo" wire:poll.10000ms="autosave"></x-editor>
提示
在 Livewire v3 中,.defer
修饰符不再可用,因为默认情况下,状态更新会被延迟。如果你需要在服务器端更新状态,可以使用 .live
修饰符,因为它会有所变化。
editor.blade.php
<div
x-data="setupEditor(
$wire.entangle('{{ $attributes->wire('model')->value() }}').defer
)"
x-init="() => init($refs.editor)"
wire:ignore
{{ $attributes->whereDoesntStartWith('wire:model') }}
>
<div x-ref="editor"></div>
</div>
index.js
import { Editor } from '@tiptap/core'
import StarterKit from '@tiptap/starter-kit'
window.setupEditor = function (content) {
let editor
return {
content: content,
init(element) {
editor = new Editor({
element: element,
extensions: [StarterKit],
content: this.content,
onUpdate: ({ editor }) => {
this.content = editor.getHTML()
},
})
this.$watch('content', (content) => {
// 如果新内容与 Tiptap 的内容相同,我们就跳过。
if (content === editor.getHTML()) return
/*
否则,意味着外部源(如 Livewire 本身)
正在修改此 Alpine 组件中的数据。
在这种情况下,我们只需要更新 Tiptap 的内容,完成即可。
更多关于 `setContent()` 方法的信息,参见:
https://www.tiptap.dev/api/commands/set-content
*/
editor.commands.setContent(content, false)
})
},
}
}