Vue + Electron 实战项目
核对 Vue + Electron 桌面笔记应用 VueElectronNotes 的项目初始化、主进程多窗口与系统托盘、preload 安全通信桥、Vue 列表视图与弹出编辑页及开发打包命令。
学完这一章,你能够
- 核对 Vue + Electron 桌面笔记应用 VueElectronNotes 的项目初始化、主进程多窗口与系统托盘、preload 安全通信桥、Vue 列表视图与弹出编辑页及开发打包命令。
项目功能规划与初始化配置
`VueElectronNotes` 是结合 Vue 前端渲染与 Electron 桌面能力的完整笔记实战项目(尚未熟悉 Vue 基础的读者可先学习本站 Vue 教程)。项目覆盖六大功能:主窗口展示笔记列表、新建笔记弹出子窗口、最小化到系统托盘、本地文件持久化保存与读取,以及渲染进程与主进程的安全 IPC 通信。初始化时可使用 `vue create VueElectronNotes`(选择默认 Babel + ESLint preset;现代新项目亦常选用 Vite + `create-vue`),随后安装开发依赖 `electron`、`electron-builder`、`concurrently`、`wait-on` 以及持久化依赖 `electron-store`。
主进程多窗口、系统托盘与环境路由
主进程文件 `electron-main.js` 统筹四个核心对象:`mainWindow` 按环境变量在开发态加载 `http://localhost:8080`、生产态加载 `dist/index.html`,并配置 `contextIsolation: true`、`nodeIntegration: false` 与 `preload.js`;监听 `minimize` 事件调用 `e.preventDefault()` 与 `mainWindow.hide()` 缩至托盘;`noteWindow` 以 `parent: mainWindow`、`modal: true` 承载新建笔记弹窗;`Tray` 挂载图标与“显示主窗口/退出”右键菜单;`ipcMain` 分别通过 `handle('get-notes')` 读取列表与 `on('save-note')` 追加写入 `electron-store` 后向主窗口广播 `update-notes`。本站离线实测(`main_window_tray_and_env_routing`)核验了开发/生产入口切换、最小化拦截隐藏、托盘恢复及安全 `webPreferences` 契约。
Preload 通信桥、Vue 列表组件与新建弹窗
`preload.js` 通过 `contextBridge.exposeInMainWorld('electronAPI', { getNotes, saveNote, onUpdateNotes })` 安全暴露异步查询、保存发送与更新订阅三个接口。`src/App.vue` 在 `mounted()` 钩子中先调用 `getNotes()` 初始化响应式 `notes` 数组,再订阅 `onUpdateNotes` 实时刷新 `v-for` 列表,点击“新建笔记”触发弹窗(工程中推荐通过 IPC 让主进程调用 `createNoteWindow()` 以复用安全 `preload`,或配置 `setWindowOpenHandler` 控制 `window.open`)。本站离线实测(`preload_ipc_and_store_sync`)基于临时目录 JSON 持久化验证了 `saveNote` 落盘并同步驱动 Vue 状态更新至 2 条笔记。
子窗口由 `note.html` 与 `note.js` 组成:用户输入内容点击保存后,`note.js` 校验非空再调用 `window.electronAPI.saveNote(note)` 发往主进程并关闭窗口,主窗口随即收到 `update-notes` 刷新列表。开发阶段运行 `npm run electron:serve` 可同时拉起 Vue Dev Server 与 Electron 进行实时调试;发布阶段执行 `npm run electron:build` 即可在 `dist_electron` 目录输出 Windows/macOS/Linux 可执行安装包。本站离线实测(`vue_electron_project_bootstrap_audit` 与 `note_popup_validation_and_close`)验证了项目脚本配置、空内容忽略及非空保存触发关闭逻辑。
离线实测 VueElectronNotes 启动配置、主进程环境路由与托盘状态、IPC/JSON 双向同步及弹窗校验
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
function caseVueElectronProjectBootstrapAudit() {
const manifest = {
name: 'VueElectronNotes',
main: 'electron-main.js',
devDependencies: ['electron', 'electron-builder', 'concurrently', 'wait-on'],
dependencies: ['electron-store'],
scripts: {
'electron:serve': 'vue-cli-service electron:serve',
'electron:build': 'vue-cli-service electron:build',
},
outputDir: 'dist_electron',
};
const actual = {
projectName: manifest.name,
mainEntry: manifest.main,
devDepCount: manifest.devDependencies.length,
hasStoreDep: manifest.dependencies.includes('electron-store'),
serveScript: manifest.scripts['electron:serve'].includes('electron:serve'),
outputDir: manifest.outputDir,
};
const expected = {
projectName: 'VueElectronNotes',
mainEntry: 'electron-main.js',
devDepCount: 4,
hasStoreDep: true,
serveScript: true,
outputDir: 'dist_electron',
};
return { name: 'vue_electron_project_bootstrap_audit', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
function caseMainWindowTrayAndEnvRouting() {
const resolveEntry = (env) => (env === 'development' ? { kind: 'url', target: 'http://localhost:8080' } : { kind: 'file', target: 'dist/index.html' });
const winState = { visible: true, minimizedPrevented: false };
const onMinimize = (event) => {
event.preventDefault();
winState.visible = false;
};
onMinimize({ preventDefault: () => { winState.minimizedPrevented = true; } });
const trayMenu = ['显示主窗口', '退出'];
const showFromTray = () => { winState.visible = true; };
showFromTray();
const webPreferences = { preload: 'preload.js', contextIsolation: true, nodeIntegration: false };
const noteWindowOptions = { width: 400, height: 300, modal: true, hasParent: true };
const actual = {
devTarget: resolveEntry('development').target,
prodTarget: resolveEntry('production').target,
minimizedPrevented: winState.minimizedPrevented,
restoredVisible: winState.visible,
trayMenu,
securePrefs: webPreferences.contextIsolation && !webPreferences.nodeIntegration,
noteModal: noteWindowOptions.modal && noteWindowOptions.hasParent,
};
const expected = {
devTarget: 'http://localhost:8080',
prodTarget: 'dist/index.html',
minimizedPrevented: true,
restoredVisible: true,
trayMenu: ['显示主窗口', '退出'],
securePrefs: true,
noteModal: true,
};
return { name: 'main_window_tray_and_env_routing', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
async function casePreloadIpcAndStoreSync() {
const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'vue-electron-'));
try {
const storePath = path.join(tmpDir, 'vue-notes.json');
const readStore = () => (fs.existsSync(storePath) ? JSON.parse(fs.readFileSync(storePath, 'utf8')) : { notes: [] });
const writeStore = (notes) => fs.writeFileSync(storePath, JSON.stringify({ notes }), 'utf8');
const updateListeners = [];
const electronAPI = Object.freeze({
getNotes: async () => readStore().notes,
saveNote: (note) => {
const notes = readStore().notes;
notes.push(note);
writeStore(notes);
for (const cb of updateListeners) cb({}, notes);
},
onUpdateNotes: (cb) => updateListeners.push(cb),
});
const vueState = { notes: await electronAPI.getNotes() };
electronAPI.onUpdateNotes((_event, notes) => { vueState.notes = [...notes]; });
electronAPI.saveNote('学习 Vue + Electron IPC');
electronAPI.saveNote('配置系统托盘最小化');
const actual = {
apiKeys: Object.keys(electronAPI),
vueReactiveNotes: vueState.notes,
persistedCount: readStore().notes.length,
};
const expected = {
apiKeys: ['getNotes', 'saveNote', 'onUpdateNotes'],
vueReactiveNotes: ['学习 Vue + Electron IPC', '配置系统托盘最小化'],
persistedCount: 2,
};
return { name: 'preload_ipc_and_store_sync', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
} finally {
await fsp.rm(tmpDir, { recursive: true, force: true });
}
}
function caseNotePopupValidationAndClose() {
const sent = [];
let closedCount = 0;
const submitNote = (raw) => {
if (raw) {
sent.push(raw);
closedCount += 1;
}
};
submitNote('');
submitNote('新笔记内容');
const actual = {
sentNotes: sent,
closedCount,
emptyIgnored: sent.length === 1,
};
const expected = {
sentNotes: ['新笔记内容'],
closedCount: 1,
emptyIgnored: true,
};
return { name: 'note_popup_validation_and_close', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
const cases = [
caseVueElectronProjectBootstrapAudit(),
caseMainWindowTrayAndEnvRouting(),
await casePreloadIpcAndStoreSync(),
caseNotePopupValidationAndClose(),
];
console.log(JSON.stringify({ version: process.version, cases }));
- 核对 VueElectronNotes 依赖与 dist_electron 配置、dev/prod 入口与托盘最小化恢复、2 条笔记落盘同步更新及空输入拦截。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
当前源码 SHA256:229fd12b0eb44ebb0817718beafdb50369ae266e529c7c54f1cf5461659e4f67
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
ZIP SHA256:1a8a0531114cb6eb593fdc417b249241826e13c4b5a85e410a3d7c928b3a1cca
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 VueElectronNotes 中,为什么主进程保存新笔记后还要主动向 mainWindow.webContents.send('update-notes', notes)?
展开参考解答
主窗口与新建笔记弹窗运行在各自独立的渲染进程中,内存状态互不共享;主进程完成本地持久化后主动广播 update-notes,才能让主窗口中的 Vue 响应式 notes 列表即时刷新。