[英]How to add a custom button to the grapesjs toolbar?
How do you add a custom button to the grapesjs toolbar?你如何在grapesjs工具栏上添加一个自定义按钮?
I have followed the instructions on this github issue and written the code below, but the button doesn't appear in the toolbar as expected.我已按照此 github 问题的说明操作并编写了下面的代码,但该按钮未按预期出现在工具栏中。
What am I missing?我错过了什么?
initToolbar() {
const { em } = this;
const model = this;
const ppfx = (em && em.getConfig('stylePrefix')) || '';
if (!model.get('toolbar')) {
var tb = [];
if (model.collection) {
tb.push({
attributes: { class: 'fa fa-arrow-up' },
command: ed => ed.runCommand('core:component-exit', { force: 1 })
});
}
if (model.get('draggable')) {
tb.push({
attributes: {
class: `fa fa-arrows ${ppfx}no-touch-actions`,
draggable: true
},
//events: hasDnd(this.em) ? { dragstart: 'execCommand' } : '',
command: 'tlb-move'
});
}
if (model.get('schedule')) {
tb.push({
attributes: { class: 'fa fa-clock', },
command: 'tlb-settime'
});
}
if (model.get('copyable')) {
tb.push({
attributes: { class: 'fa fa-clone' },
command: 'tlb-clone'
});
}
if (model.get('removable')) {
tb.push({
attributes: { class: 'fa fa-trash-o' },
command: 'tlb-delete'
});
}
model.set('toolbar', tb);
}
},
One way to add new toolbar icons is to add the button as each component is selected.添加新工具栏图标的一种方法是在选择每个组件时添加按钮。
// define this event handler after editor is defined
// like in const editor = grapesjs.init({ ...config });
editor.on('component:selected', () => {
// whenever a component is selected in the editor
// set your command and icon here
const commandToAdd = 'tlb-settime';
const commandIcon = 'fa fa-clock';
// get the selected componnet and its default toolbar
const selectedComponent = editor.getSelected();
const defaultToolbar = selectedComponent.get('toolbar');
// check if this command already exists on this component toolbar
const commandExists = defaultToolbar.some(item => item.command === commandToAdd);
// if it doesn't already exist, add it
if (!commandExists) {
selectedComponent.set({
toolbar: [ ...defaultToolbar, { attributes: {class: commandIcon}, command: commandToAdd }]
});
}
});
If it's important to you that only components with the "schedule" attribute have this toolbar option show up, as in your example, you can access and check this from selectedComponent:如果只有具有“schedule”属性的组件才会显示此工具栏选项对您很重要,如您的示例中所示,您可以从 selectedComponent 访问并检查它:
const selectedComponent = editor.getSelected();
const defaultToolbar = selectedComponent.get('toolbar');
const commandExists = defaultToolbar.some(item => item.command === commandToAdd);
// add this
const hasScheduleAttribute = selectedComponent.attributes.schedule;
if (!commandExists && hasScheduleAttribute) { // ...set toolbar code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.