1
votes

I'm creating a cross platform electron app using vuejs and vue-cli-electron-builder plugin. I have some input field in a form that will give to the user the ability to submit a form with some attached files and I want to process the files in the background process of the app. How I can send the data from the vue UI to the main process of the electron app?

1

1 Answers

2
votes

There are two processes in electron, the main process, and the renderer process. A Vue component runs on the renderer process. Writing files, however, runs on the main process which is usually represented by background.js. We need a way to communicate between these two processes to write the data. That way is called inter-process communication. electron provides ipcMain & ipcRenderer to communicate between the two processes.

Suppose you need to send data from the form (Vue component) to the main process. We start by defining a custom event in background.js such as:

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));

In your Vue component, you'd do the following:

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)
          }
     }
}

You could also communicate data the other way around, i.e. from the main process to the renderer process. Read more here: https://www.electronjs.org/docs/api/ipc-main and here https://www.electronjs.org/docs/api/ipc-renderer

You might get an error message like "dirname is not found". The fix to that is to add the following code to vue.config.js

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

};