微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

electron 主进程与渲染进程通信的具体教程

1:渲染层事件中心

 
@H_404_6@
  1. const ipcRenderer = require('electron').ipcRenderer;

  2. const sendBridge = (msg = { active: '', data: {} }) => {

  3. return new Promise((resolve, reject) => {

  4. ipcRenderer.on(msg.active, (event, arg) => {

  5. resolve(arg);

  6. });

  7. console.log('8>>>bridge.js', msg);

  8. ipcRenderer.send(msg.active, msg);

  9. });

  10. };

  11. export default sendBridge;

1.2 渲染层 事件中心注册

 
@H_404_6@
  1. import Vue from 'vue';

  2.  
  3. import sendBridge from './events/bridge';

  4.  
  5. Vue.prototype.$sendBridge = sendBridge;

 

2:主进程 接收并处理

index.js 注册IPCHandler

 
@H_404_6@
  1. import IPCHandler from './IPCHandler';

  2. let context = {}; // 全局上下文

  3. context.app = app;

  4. context.isDev = process.env.NODE_ENV !== 'production';

  5. context.ipcHandler = new IPCHandler(context);

IPCHandler.js

 
@H_404_6@
  1. const { ipcMain } = require('electron');

  2. class IPCHandler {

  3. constructor (context) {

  4. this.mContext = null;

  5. this.mContext = context;

  6. // 通讯录

  7. ipcMain.on('onInsertAllContacts', this.onInsertAllContacts.bind(this));

  8. }

  9. async onInsertAllContacts (event, args, userInfo) {

  10. console.log(38, event, args);

  11. event.sender.send(args.active, { active: args.active, result });

  12. }

  13. }

  14. export default IPCHandler;

3:渲染层 调用

 
@H_404_6@
  1. this.$sendBridge({active: 'onInsertAllContacts', data: []}).then(res => {

  2. });

 

 

总体思路:

页面组件 (active) =》 事件中心(ipcRenderer active) =》主进程接收中心(ipcMain active)=》【主进程业务处理】=》主进程接收中心(ipcRenderer callback)=》页面组件 (active,callback)

另外本人这里有套关于小白学习的大量资料,有兴趣的同学可以点击这里

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐