Vue3调用Electron IPC方法返回undefined问题求助
问题解决:Electron preload脚本异步IPC返回undefined
问题原因
你的func方法是同步执行逻辑:发送IPC请求后立刻返回data,但此时ipcRenderer.once的回调还未触发(主进程的响应还没返回),所以data始终是初始的undefined。异步操作的结果无法通过同步返回的方式获取。
解决方案
把func改成返回Promise,在IPC响应的回调里resolve数据,这样就能在Vue中通过await或.then()拿到异步结果。
修改后的preload脚本
import { contextBridge, ipcRenderer } from 'electron'; contextBridge.exposeInMainWorld('electron', { func: (/* 你的参数 */) => { const input = { // 你的参数配置,需包含responseId }; // 返回Promise包裹异步逻辑 return new Promise((resolve) => { ipcRenderer.once( 'response-' + input.responseId, function (event, reply) { const data = JSON.parse(reply); resolve(data); // 拿到响应数据后resolve Promise } ); ipcRenderer.send('request', input); }); }, });
Vue中调用代码
使用async/await:
async function fetchData() { const result = await window.electron.func(/* 传入参数 */); console.log(result); // 此处可获取正确的响应数据 } fetchData();
或者使用.then()链式调用:
window.electron.func(/* 传入参数 */) .then(result => { console.log(result); });
主进程注意事项
确保主进程中使用的responseId与input.responseId完全一致,否则监听的事件名不匹配,Promise会一直处于pending状态无法resolve。
内容的提问来源于stack exchange,提问作者Cameron Fitzpatrick
相关产品推荐
相关产品推荐

