javascript - 如何在grapesjs工具栏中添加自定义按钮?
问题描述
你如何在grapesjs工具栏上添加一个自定义按钮?
我已按照此 github 问题上的说明编写了下面的代码,但该按钮未按预期出现在工具栏中。
我错过了什么?
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);
}
},
解决方案
添加新工具栏图标的一种方法是在选择每个组件时添加按钮。
// 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 }]
});
}
});
如果只有具有“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
推荐阅读
- vba - 范围缺失值检查时出现运行时错误 91
- python - 如何将exe转换回Python脚本
- javascript - 在函数计时器上返回未定义的 img
- python - Python argparse 的可选位置参数
- mongodb - 将对象属性(字符串)设置为文本索引
- python - Python 3 枚举列表值不支持成员资格测试
- arrays - Fortran 运行时错误:可分配数组的文件结尾
- git - GIT:在意外提交并推送删除文件后,您能否恢复文件的最新工作版本?
- mysql - 如果行存在,则 SQL 运行命令
- spring - Spring Batch - 在使用 FlatFileItemWriter API 写入数据时创建新的唯一 CSV 名称