蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线实测 VueElectronNotes 启动配置、主进程环境路由与托盘状态、IPC/JSON 双向同步及弹窗校验

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-vue-electron.mjs
explore-vue-electron.mjs149 行
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 }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Node.js v24.22.3 本地运行环境。

入口文件:projects/electron-vue-electron-lab/explore-vue-electron.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-vue-electron.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Electron

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a1081.zip

下载课程关联工程包:Electron

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1098.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习