Electron-渲染进程和主进程通信 渲染进程调用ipcRenderer进行发送
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 <!-- * @Description: * @Author: xiuji * @Date: 2023-01-11 10:22:30 * @LastEditTime: 2023-01-17 14:43:58 * @LastEditors: Do not edit --> <script setup lang="ts"> import { ref } from 'vue' import {ipcRenderer} from 'electron' defineProps<{ msg: string }>() const count = ref(0) const send = () => { count.value++ // 渲染进程使用ipcRenderer发送 ipcRenderer.send('message',count.value) } </script> <template> <h1>{{ msg }}</h1> <div class="card"> <button type="button" @click="send">count is {{ count }}</button> <p> Edit <code>components/HelloWorld.vue</code> to test HMR </p> </div> <p> Check out <a href="https://vuejs.org/guide/quick-start.html#local" target="_blank" >create-vue</a >, the official Vue + Vite starter </p> <p> Install <a href="https://github.com/johnsoncodehk/volar" target="_blank">Volar</a> in your IDE for a better DX </p> <p class="read-the-docs">Click on the Vite and Vue logos to learn more</p> </template> <style scoped> .read-the-docs { color: #888; } </style>
主进程使用ipcMain接收
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 import { app, BrowserWindow , ipcMain } from 'electron' import path from 'path' const createWindow = ( ) => { const win = new BrowserWindow ({ width : 1200 , height : 900 , webPreferences : { devTools : true , contextIsolation : false , nodeIntegration : true } }) if (app.isPackaged ) { win.loadFile (path.join (__dirname, '../index.html' )) } else { win.loadURL (`${process.env.VITE_DEV_SERVER_URL} ` ) win.webContents .openDevTools (); } ipcMain.on ('message' , (e, iterm ) => { console .log (iterm, '收到' ); }) } app.whenReady ().then (createWindow)
启动项目报错
安装vite-plugin-electron-renderer
1 pnpm i vite-plugin-electron-renderer -D
配置vite.config.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import electron from 'vite-plugin-electron' import electronRender from 'vite-plugin-electron-renderer' export default defineConfig ({ plugins : [vue (), electron ({ entry : 'electron/index.ts' }), electronRender ()], })
成功启动项目,渲染进程与主进程通信成功
主进程与渲染进程通信 主进程发送
1 2 3 4 setTimeout (() => { win.webContents .send ('load' , { msg : '主进程发来贺电' }) }, 2000 );
渲染进程使用ipcRenderer接收
1 2 3 ipcRenderer.on('load', (e, i) => { console.log(i,'渲染进程接收'); })
成功