CKEditor5 UI——UI组件

百科知识2025-04-261

CK5提供了一个标准UI库,这个库是由@ckeditor/ckeditor5-ui实现的。

我们首先需要理解的是CK5的UI组件都是用模板来构建的,因此,我们首先明白什么是模板?UI组件在CK中又称为视图,视图是模板通过渲染后得到的。

视图

首先,我们定义一个视图:

import {View} from 'ckeditor5/src/ui';
export default class InputView extends View {
constructor(locale) {
super(locale);

    const bind = this.bindTemplate;

    // 定义两个可观测属性,因为InputView 继承自View,
    // View属于Observable,所以可以直接定义
    this.set({
        isEnabled: false,
        placeholder: ''
    });

    this.setTemplate({
        tag : 'input',
        attributes: {
            class: [
                'foo',
                bind.if('isEnabled','ck-enabled')
            ],

            placeholder: bind.to('placeholder'),
            type: 'text'
        },
        on: {
            keydown: bind.to('input')
        }
    });
}

setValue(newValue){
    this.element.value = newValue;
}

}

然后我们定义一个包含以上视图的父视图

import {View} from 'ckeditor5/src/ui';
import InputView from './inputview';
export default class ParentView extends View {
constructor(locale) {
super(locale);
const childA = new InputView();
const childB = new InputView();

    this.setTemplate({
        tag: 'div',
        children: [
            childA,
            childB
        ]
    });
}

}

最后在一个UI组件中调用

const parent = new ParentView(locale);
parent.render();
document.body.appendChild( parent.element );

最后我们可以在页面看到两个输入框,如下图所示

我们可以看到视图对应的html如上所示,注意,这部分不属于ck的编辑视图区,这点一定要注意。

我们首先来分析代码,在我们的模板中又一个placeholder属性,但是在生成的标签中却没有这属性,为啥呢,怎么样才能让这个属性数显呢?

怎么样才能修改input输入框的值?

第一步,我在ParentView中显然不能修改子视图的值,因此我需要将这两个视图导出来。

const childA = new InputView();
this.childA = childA;
childA.isEnabled = true;
const childB = new InputView();
this.childB = childB;

并且增加两个方法:

getChildA() {
return this.childA;
}
getChildB() {
return this.childB;
}

然后我在调用代码出增加:

parent.childA.setValue(8888888);
parent.childA.placeholder = '88888';

可以看到,我这里把A视图的相关的值已经修改,因此,大家应该能理解怎么构建视图了吧。

这里还有一点需要注意的是,如果子视图还没有渲染的时候,这个时候调用setValue()方法,这个时候会报错:

我们依旧用代码说明,在ParentView的构造函数中增加一行代码:

const childA = new InputView();
childA.setValue(8888); //增加的代码

因为视图还没有渲染,所以设置值是无效的,那么如果我增加一个渲染方法呢?

const childA = new InputView();
childA.render();
childA.setValue(8888);

这个时候就能获得正确的值了。

因此,我们总结出来一条:

视图的方法必须在渲染后才能调用。

最后一个问题,怎么样监听input的输入事件,我的理解是可以通过on或者listenTo方法,我们还是用代码来说明:

如果在InputView视图中

this.on('input',(evt,data)=>{
console.log('data:',data)
});

如果是在ParentView视图中

this.listenTo(childA,'input',(evt,data)=>{
console.log(evt);
console.log('parentView:',data);
});

this.listenTo(childB,'input',(evt,data)=>{
console.log(evt);
console.log('parentView:',data);
});

当我输入一些值的时候,

回调函数会执行

好了,今天的知识就是这么多了,欢迎交流和讨论。