第一种通信方法:
在vue框架中要有主进程和渲染进程,每个进程都有个web页面,即BrowserWindow对象,此BrowserWindow对象是在主进程中创建的。进程和页面之间可以通信,主进程向渲染进程中发送消息时,调用webContents.send(id, data)方法,渲染进程使用ipcRenderer.on()方法监听数据。
1. Main主进程
import { ipcMain } from 'electron' //导入ipcMain
let webContents //webContents对象
webContents = mainWindow.webContents //这个mainWindow一定是Main进程new的BrowserWindow对象
# 发送
function SendMsg (id, data) {
webContents.send(id, data) //给渲染进程发送消息,id是特有的,data就是数据
}
# 接收
ipcMain.on(IPC_CHANNEL_START_DOWNLOAD, (event, arg) => {
console.log("msg >>", arg)
})
2. Renderer进程
import { ipcRenderer } from 'electron' //导入ipcRenderer
# 接收
ipcRenderer.on(id, (event, arg) => {
console.log('Data >>', arg) //arg就是Main进程传输来的数据,id必须一致,否则接收无效
})
# 发送
ipcRenderer.send(IPC_CHANNEL_START_DOWNLOAD, "data") //
第二种通信方法:
main 端用 ipcMain, renderer 端用 ipcRenderer, 通讯逻辑书写复杂,如果是两个渲染界面中通信,那么就要通过main端进行中转。当然在vue中有推荐了我们去使用vuex去数据交互,Vuex会让你的Vue代码足够灵活可控,把数据统一存入state, 只允许通过Actions触发Mutations修改。然而,有时候我们的项目并没有复杂到需要用上Vuex。,(我们也不讨论已经废除的vm.$dispatch)很多情况下我们都是需要一个事件的捕获,这时候我们就可以用到vue的eventbus了。
1. 全局定义使用EventBus
// EventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
2. 提交事件
//渲染进程A
import { EventBus } from "../../utils/EventBus"; //引入EventBus
//提交状态EVNT_COMM_SHOW_STATIUS就是固定的id
EventBus.$emit(EVNT_COMM_SHOW_STATIUS, "your message");
3. 监听事件
//渲染进程B
import { EventBus } from "../../utils/EventBus"; //引入EventBus
//监听事件EVNT_COMM_SHOW_STATIUS就是固定的id
EventBus.$on(EVNT_COMM_SHOW_STATIUS, arg => {
console.log("printf >>", arg);
});
推荐使用第二种方法,这样子在做渲染界面通讯时更加灵活。