项目

Vue.js 3 文本编辑器 tiptap 集成指南

引言

以下指南将指导您如何将 Tiptap 与您的 Vue CLI 项目集成。

需要条件

  • Node.js 已在您的机器上安装
  • Vue CLI 已在您的机器上安装
  • Vue 有基本了解

1. 创建项目(可选)

如果您已经有了现有的 Vue 项目,也可以直接跳过此步骤。继续进行下一步即可。

为了演示,我们从一个名为 my-tiptap-project 的新 Vue 项目开始。Vue CLI 会为我们准备好所有需要的配置。

# 创建项目
vue create my-tiptap-project

# 移动到项目目录
cd my-tiptap-project

2. 安装依赖

现在,让我们安装 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。如果您的项目不同,则可能会有所不同。

3. 创建新组件

为了使用 Tiptap,我们需要在应用中添加一个新的组件。我们将这个组件命名为 Tiptap,并在 components/Tiptap.vue 中放置以下示例代码。

这是使用 Vue 快速启动 Tiptap 的最简单方法。它提供了一个基础版本的 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>

或者,你可以使用 Composition API 通过 useEditor 方法。

<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>

4. 将组件添加到应用

现在,我们将 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 了。给自己一个大大的赞! :)

5. 使用 v-model(可选)

您可能习惯于在表单中使用 v-model 绑定数据。在 Tiptap 中,这同样可行。以下是使用 v-model 的示例:

Tiptap v-model 示例

在本文档中