Contribute to this guide

guide编辑器生命周期

每个 CKEditor 5 类型都提供一个不同的 编辑器类,用于处理编辑器实例的创建。文档中的大多数示例都使用 ClassicEditor 类,但其他类型的工作方式应该类似。

# 使用 create() 创建编辑器

无论选择哪种类型,创建编辑器都是通过使用静态的 create() 方法完成的。通常,您从一个 HTML 元素开始,该元素将作为编辑器在页面上渲染自己的位置。

每个编辑器类都可以在 create() 方法中接受不同的参数,并可能以不同的方式处理初始化。例如,经典编辑器将 替换 给定的元素,而内联编辑器将使用给定的元素在其上初始化编辑器。分离式文档编辑器需要在可编辑区域之外单独初始化工具栏。请参阅每个编辑器的文档以了解详细信息。

# 示例:经典编辑器

在您的 HTML 页面中添加 CKEditor 5 应该替换的元素

<div id="editor">
    <p>Here goes the initial content of the editor.</p>
</div>

然后,您调用 ClassicEditor.create()替换 <div> 元素,创建一个经典编辑器

import { ClassicEditor, Essentials } from 'ckeditor5';

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        plugins: [ Essentials, /* ... */ ],
    } )
    .then( editor => {
        console.log( editor );
    } )
    .catch( error => {
        console.error( error );
    } );

创建后,编辑器将出现在页面上的所选区域。

内联和气泡编辑器类型的初始化方式相同。

# 示例:分离式编辑器

在页面中添加 CKEditor 5 应该初始化工具栏和可编辑区域的元素

<!-- The toolbar will be rendered in this container. -->
<div id="toolbar-container"></div>

<!-- This container will become the editable. -->
<div id="editor">
    <p>This is the initial editor content.</p>
</div>

然后,调用 DecoupledEditor.create() 方法,使用两个独立的容器创建一个分离式编辑器实例,分别包含工具栏和可编辑区域

import { DecoupledEditor, Essentials } from 'ckeditor5';

DecoupledEditor
    .create( document.querySelector( '#editor' ), {
        plugins: [ Essentials, /* ... */ ],
    } )
    .then( editor => {
        const toolbarContainer = document.querySelector( '#toolbar-container' );

        toolbarContainer.appendChild( editor.ui.view.toolbar.element );
    } )
    .catch( error => {
        console.error( error );
    } );

# 获取编辑器的实例

最简单的方法是在创建编辑器后将对它的引用保存到某个位置。这通常是通过使用窗口或某些状态管理对象完成的。您经常会在我们的文档中看到类似的代码行。

// Editor's creation steps.
// ...
.then( editor => {
    window.editor = editor;
})

// Or with the await (if your setup supports it):
const editor = await ClassicEditor.create( /* ... */  );

# 使用 destroy() 销毁编辑器

在现代应用程序中,通过 JavaScript 交互式地创建和删除页面元素很常见。在这种情况下,应该使用 destroy() 方法销毁 CKEditor 5 实例

editor
    .destroy()
    .catch( error => {
        console.log( error );
    } );

销毁后,编辑器实例使用的资源将被释放,用于创建编辑器的原始元素将自动显示并更新以反映最终的编辑器数据。