本指南展示如何在 Vue.js 应用程序中使用 TinyMCE Vue.js 组件 自行托管并懒加载 TinyMCE。

先决条件

此过程需要:

步骤

  1. 使用 Create Vue 工具创建一个名为 tinymce-vue-demo 的新 Vue 项目。

    • 在命令行或命令提示符中,创建 Vue.js 3.x 项目:tinymce-vue-demo。

      npm create vue@3
    • 如果需要 Vue.js 2.x 项目,请使用:

      npm create vue@2
    • 按照提示操作,并将项目名称输入为 tinymce-vue-demo。

  2. 进入新创建的目录。

    cd tinymce-vue-demo
  3. 安装 tinymce 和 tinymce-vue 包。

    • 对于 Vue.js 3.x 用户:

      npm install tinymce @tinymce/tinymce-vue
    • 对于 Vue.js 2.x 用户:

      npm install tinymce @tinymce/tinymce-vue@^3
  4. 使用以下代码片段更新 App.vue。注意:tinymceSrcScript 引用了使用绝对根路径的公共 tinymce。例如:

    <script setup>
    import Editor from '@tinymce/tinymce-vue';
    </script>
    
    <template>
      <main id="sample">
        <img alt="Vue logo" class="logo" src="./assets/logo.svg" width="125" height="125" />
        <Editor
          id="<uid>"
          licenseKey="gpl"
          // Load tinymce at run-time
          tinymce-script-src="/tinymce/tinymce.min.js"
          :init="{
            plugins: 'anchor lists advlist autolink charmap code media help',
            toolbar: 'undo redo | styles | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
            height: 500
          }"
        />
      </main>
    </template>
    
    <style scoped>
    .logo {
      display: block;
      margin: 0 auto 2rem;
    }
    
    @media (min-width: 1024px) {
      #sample {
        display: flex;
        flex-direction: column;
        place-items: center;
        width: 1000px;
      }
    }
    </style>
  5. 设置一个 postinstall 脚本,以便在每次安装包后将 TinyMCE 复制到 public 目录,使 TinyMCE 作为静态资源对应用程序可用。

    1. 安装一个用于辅助复制资源的库。

      npm install -D fs-extra
    2. 将以下代码片段添加到 postinstall.js 文件中。

      import fse from 'fs-extra';
      import path from 'path';
      
      const topDir = import.meta.dirname;
      fse.emptyDirSync(path.join(topDir, 'public', 'tinymce'));
      fse.copySync(path.join(topDir, 'node_modules', 'tinymce'), path.join(topDir, 'public', 'tinymce'), { overwrite: true });
    3. 更新 package.json 中的 postinstall 目标以运行 postinstall.js 脚本。

      // ... other content omitted for brevity ...
      "scripts": {
        "postinstall": "node ./postinstall.js"
      }
  6. 将 public/tinymce 排除在 Git 跟踪之外。

    # ... other rules omitted for brevity ...
    /public/tinymce/
  7. 在此实例中,运行 postinstall 以将 TinyMCE 复制到 public 目录。

    npm run postinstall
  8. 要启动开发服务器,请运行:

    npm run dev

其他资源