【问题标题】:vue-electron-builder plugin - passing form data from vue to main electron processvue-electron-builder 插件 - 将表单数据从 vue 传递到主电子进程
【发布时间】:2021-03-16 11:14:14
【问题描述】:

我正在使用 vuejs 和 vue-cli-electron-builder 插件创建一个跨平台的电子应用程序。我在表单中有一些输入字段,使用户能够提交带有一些附件的表单,我想在应用程序的后台进程中处理这些文件。如何将数据从 vue UI 发送到电子应用程序的主进程?

【问题讨论】:

    标签: forms vue.js electron-builder


    【解决方案1】:

    electron中有两个进程,主进程和renderer进程。一个 Vue 组件在渲染器进程上运行。但是,写入文件在通常由background.js 表示的主进程上运行。我们需要一种方法在这两个进程之间进行通信以写入数据。这种方式称为inter-process communication。 electron 提供ipcMain & ipcRenderer 来实现两个进程之间的通信。

    假设您需要将数据从表单(Vue 组件)发送到主进程。我们首先在background.js 中定义一个自定义事件,例如:

    import {ipcMain} from "electron"; 
    
    // this is the event listener that listens to the event emitted by the Vue component
    ipcMain.on("form-submission-event", (event, args) => writeFormData(args));
    

    在您的 Vue 组件中,您将执行以下操作:

    import {ipcRenderer} from "electron";
    
    export default defineComponent({
         methods: {
             submitForm(data){
               // this will send the data to the main process
              ipcRenderer.send("form-submission-event", data)
              }
         }
    }
    

    您还可以通过其他方式传递数据,即从主进程到渲染器进程。在此处阅读更多信息:https://www.electronjs.org/docs/api/ipc-main 和此处https://www.electronjs.org/docs/api/ipc-renderer

    您可能会收到“找不到目录名”之类的错误消息。解决方法是将以下代码添加到vue.config.js

    module.exports = {
      pluginOptions: {
        electronBuilder: {
          nodeIntegration: true
        }
      }
    

    };

    【讨论】:

    • 感谢您的回答,我尝试添加 nodeIntegration,但是当我在服务模式 ReferenceError: __dirname is not defined 下运行应用程序时出现此错误。我已经尝试重新启动该过程,但错误仍然存​​在,我不确定是什么问题
    • 你用的是哪个版本的 Vue 和 electron?另外,您使用的是npm run electron:serve 吗?还是您收到npm run serve 的错误?
    • 我正在使用vue/cli 4.3.1,并且我正在使用 vue ui 创建项目,对于电子生成器插件,我正在使用 "vue-cli-plugin-electron-builder": "^2.0.0-rc.5" 内部使用电子 "electron": "^9.0.0" 的版本。我正在使用来自 vue ui 的npm run electron:serve 命令
    • 好的,你能升级到electron 11吗?也许这会有所帮助。
    • 我正在尝试全局更新它,但是当我从 macOS 终端运行electron -v 时,我得到v3.0.0。我尝试运行npm uninstall electron && npm install electron@latest -g,但它会始终安装@ 987654343@也许我做错了?
    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2017-02-24
    • 2019-03-28
    • 2020-09-25
    • 2021-08-07
    • 2019-07-12
    • 1970-01-01
    相关资源
    最近更新 更多