美文网首页
CKEditor 5简单封装使用

CKEditor 5简单封装使用

作者: A一土彳曰于丶金金金 | 来源:发表于2024-01-01 02:24 被阅读0次

    记录一下日常,封装CKEditor 5,函数里每次初始化CKEditor 5 的时候,把editor输出到全局变量。因为重复使用初始化,导致全局变量只显示最后初始化的editor。

    要解决这个问题,我们需要确保每次调用 createEditor 函数时,都能正确地将新的 editor 实例存储到一个地方,而且这个地方不会因为重复调用而覆盖之前的实例。我们可以通过以下几种方法来解决这个问题:

    1. 使用一个数组来存储所有的 editor 实例,每个实例都关联到相应的 editorId。
    2. 使用一个对象,其中 key 是 editorId,value 是对应的 editor 实例。
    3. 使用一个映射(Map),其中 key 是 editorId,value 是对应的 editor 实例。

    代码

    // 用一个对象来存储所有编辑器实例
    const editors = {};
    
    function createEditor(editorId, content) {
        // 检查编辑器是否已存在
        if (editors[editorId]) {
            console.error(`id为"${editorId}"的编辑器已存在。`);
            return;
        }
    
        // 创建新的编辑器实例
        ClassicEditor
            .create(document.querySelector(`#${editorId}`), {
                toolbar: {},
                placeholder: content,
            })
            .catch(error => {
                console.error(error);
            })
            .then(editor => {
                // 将编辑器实例存储到全局对象中
                editors[editorId] = editor;
            });
    }
    
    function setContext(editorId, content) {
        // 获取编辑器实例
        const editor = editors[editorId];
        if (editor) {
            // 设置编辑器的内容
            editor.setData(content);
        } else {
            console.error(`id为"${editorId}"的编辑器不存在。`);
        }
    }
    

    使用方法

    // 初始化第一个编辑器
    createEditor('notice1', '请输入公告内容1');
    // 初始化第二个编辑器
    createEditor('notice2', '请输入公告内容2');
    // 设置第一个编辑器的内容
    setContext('notice1', '这是第一个编辑器的内容');
    // 设置第二个编辑器的内容
    setContext('notice2', '这是第二个编辑器的内容');
    
    //获取编辑器内容
    //editors是存储所有编辑器实例,详情见上面第一块第二行带代码
    const editor = editors['notice1'];
    console.log(editor.getData()); //输出:这是第一个编辑器的内容
    
    

    每次调用 createEditor 函数时,都会检查该 editorId 是否已存在。如果已存在,会打印一个错误信息。如果不存在,就会创建一个新的编辑器实例,并将其存储到 editors 对象中。这样,即使你多次调用 createEditor 函数,也不会覆盖之前的编辑器实例。
    同样地,当你调用 setContext 函数时,它会检查 editors 对象中是否存在对应的 editor 实例。如果存在,就会更新其内容;如果不存在,会打印一个错误信息。

    相关文章

      网友评论

          本文标题:CKEditor 5简单封装使用

          本文链接:https://www.haomeiwen.com/subject/zwxundtx.html