我是电子新手,我正在尝试创建一个Mac菜单栏应用程序,其中包含动态菜单项。我的想法是单击“添加...”时,会在其中添加/添加/插入新菜单项。
我的代码将新项目追加到菜单数组中。但是我无法使其呈现“更新的菜单”。
const { resolve } = require('path');
const { app, Tray, Menu } = require('electron');
const iconPath = resolve(__dirname, 'assets','iconTemplate.png');
let contextMenu;
let tray = null;
let menu;
app.on('ready', function() {
tray = new Tray(iconPath);
menu = [
{
label: 'Add...',
click: function() {
// add new item between 'Add...' and 'Quit'. New one always on top of the last.
menu.push({label: 'new item'});
}
},
{
label: 'Quit',
enabled: false
}
]
contextMenu = Menu.buildFromTemplate(menu);
tray.setContextMenu(contextMenu);
});
答案 0 :(得分:0)
结果我想通了自己。
let counter = 0; // Start counter globally
// add new item between 'Add...' and 'Quit'. New one always on top of the last.
menu.splice(1, 0, {label: String(counter)});
render(); // Call render for every alteration on the menu array
counter++;
function render() {
contextMenu = Menu.buildFromTemplate(menu);
tray.setContextMenu(contextMenu);
}