在前端开发中,富文本编辑器几乎是很多项目的标配,例如 CMS 系统、博客平台、论坛和在线文档。相比传统的富文本编辑器(如 TinyMCE、CKEditor),Editor.js 以 块级编辑器(Block Style Editor) 的形式出现,更专注于结构化内容,适合现代 Web 应用的内容存储与展示。
本文将带你一步步在 Vue 项目中集成 Editor.js,并给出实际使用示例。
在 Vue 项目中使用 Editor.js,首先需要安装核心包和常用工具插件,例如标题、段落、列表等。
npm install @editorjs/editorjs @editorjs/header @editorjs/list @editorjs/paragraph
常见插件包括:
@editorjs/header
:标题@editorjs/list
:有序/无序列表@editorjs/paragraph
:段落(Editor.js 默认自带,但单独引入更灵活)如果需要图片上传、代码高亮等功能,可以根据需求安装对应插件。
这里以 Vue 3 + Composition API 为例,封装一个简单的 Editor.vue
组件。
<template>
<div>
<!-- 编辑器容器 -->
<div id="editorjs"></div>
<!-- 保存按钮 -->
<button @click="saveData">保存内容</button>
</div>
</template>
<script setup>
import { onMounted, onBeforeUnmount } from "vue";
import EditorJS from "@editorjs/editorjs";
import Header from "@editorjs/header";
import List from "@editorjs/list";
import Paragraph from "@editorjs/paragraph";
let editor = null;
onMounted(() => {
editor = new EditorJS({
holder: "editorjs", // 容器 ID
autofocus: true,
placeholder: "开始书写你的内容...",
tools: {
header: Header,
list: List,
paragraph: {
class: Paragraph,
inlineToolbar: true
}
}
});
});
// 组件卸载时销毁编辑器
onBeforeUnmount(() => {
if (editor) {
editor.destroy();
editor = null;
}
});
// 保存方法
const saveData = async () => {
try {
const outputData = await editor.save();
console.log("编辑内容:", outputData);
alert(JSON.stringify(outputData, null, 2));
} catch (error) {
console.error("保存失败:", error);
}
};
</script>
这段代码完成了:
#editorjs
。header
、list
、paragraph
三个基础工具。在实际业务中,用户可能需要二次编辑已保存的内容。Editor.js 支持通过 data
参数进行内容回显。
editor = new EditorJS({
holder: "editorjs",
tools: {
header: Header,
list: List,
paragraph: Paragraph
},
data: {
time: Date.now(),
blocks: [
{
type: "header",
data: {
text: "欢迎使用 Editor.js",
level: 2
}
},
{
type: "paragraph",
data: {
text: "这是一个在 Vue 中集成的示例。"
}
}
]
}
});
这样,加载编辑器时会自动填充已有内容。
@editorjs/image
插件,并配置 uploader
方法,与后端接口对接。onBeforeUnmount
钩子中调用 editor.destroy()
,避免内存泄漏。Editor.js 相比传统富文本编辑器,更适合需要 结构化数据存储与二次渲染 的场景,例如知识库、内容管理系统、在线文档等。通过简单的封装,就能在 Vue 项目中快速集成,并支持灵活扩展。
如果你的项目对 内容结构化、可扩展性 有较高要求,那么 Editor.js 无疑是一个值得尝试的现代化编辑器。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。