vue-electron-builder 插件 - 将表单数据从 vue 传递到主电子进程

new*_*dev 1 forms vue.js electron-builder

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

小智 5

Electron中有两个进程,主进程和渲染器进程。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));
Run Code Online (Sandbox Code Playgroud)

在您的 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)
          }
     }
}
Run Code Online (Sandbox Code Playgroud)

您还可以以相反的方式传递数据,即从主进程到渲染器进程。阅读更多信息: 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
    }
  }
Run Code Online (Sandbox Code Playgroud)

};