43,708
社区成员




这里以 Vue 3 + Composition API 为例,封装一个简单的 Editor.vue
组件。
代码语言:js
AI代码解释
<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
三个基础工具。