Vue 3
发现如何使用这份逐步指南将 Tiptap 集成到您的 Vue 3 项目中。或者,您可以查看我们的 Vue 文本编辑器示例。
要求
创建一个项目(可选)
如果您已经有了一个 Vue 项目,也没关系。只需跳过这一步。
为了本指南的目的,创建一个名为 my-tiptap-project 的新 Vue 项目。Vue CLI 会设置我们所需的一切。只需选择 Vue 3 模板。
# 创建一个项目
vue create my-tiptap-project
# 切换目录
cd my-tiptap-project安装依赖
好吧,足够的样板工作。让我们最终安装 Tiptap!在下面的示例中,您需要 @tiptap/vue-3 包,@tiptap/pm(ProseMirror 库)和 @tiptap/starter-kit,它包含了最常用的扩展,以便迅速开始。
npm install @tiptap/vue-3 @tiptap/pm @tiptap/starter-kit如果您按照步骤 1 和 2 操作,现在可以使用 npm run dev 启动项目,并在您喜欢的浏览器中打开 http://localhost:8080。如果您在处理现有项目,这可能会有所不同。
集成 Tiptap
要开始使用 Tiptap,您需要向应用中添加一个新组件。我们称它为 Tiptap,并将以下示例代码放入 components/Tiptap.vue 中。
这是让 Tiptap 在 Vue 中顺利运行的最快方法。它将为您提供一个非常基本的 Tiptap 版本,没有任何按钮。别担心,您很快就能添加更多功能。
<template>
<editor-content :editor="editor" />
</template>
<script>
import { Editor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
export default {
components: {
EditorContent,
},
data() {
return {
editor: null,
}
},
mounted() {
this.editor = new Editor({
content: "<p>我正在用 Vue.js 运行 Tiptap。🎉</p>",
extensions: [StarterKit],
})
},
beforeUnmount() {
this.editor.destroy()
},
}
</script>另外,您也可以使用 useEditor 方法的组合 API。
<template>
<editor-content :editor="editor" />
</template>
<script>
import { useEditor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
export default {
components: {
EditorContent,
},
setup() {
const editor = useEditor({
content: "<p>我正在用 Vue.js 运行 Tiptap。🎉</p>",
extensions: [StarterKit],
})
return { editor }
},
}
</script>或者,您可以自由使用新的 <script setup> 语法。
<template>
<editor-content :editor="editor" />
</template>
<script setup>
import { useEditor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
const editor = useEditor({
content: "<p>我正在用 Vue.js 运行 Tiptap。🎉</p>",
extensions: [StarterKit],
})
</script>将其添加到您的应用
现在,让我们用以下示例代码替换 src/App.vue 的内容,以在我们的应用中使用新的 Tiptap 组件。
<template>
<div id="app">
<tiptap />
</div>
</template>
<script>
import Tiptap from './components/Tiptap.vue'
export default {
name: 'App',
components: {
Tiptap,
},
}
</script>您现在应该能够在浏览器中看到 Tiptap。是时候给自己一个赞吧!:)
使用 v-model(可选)
您可能习惯于在表单中使用 v-model 将数据绑定,这在 Tiptap 中也可以。这就是 Tiptap 的实现方式: