Deluze / electron-vue-template

Simple Vue3 + Electron starter template in TypeScript, including ViteJS and Electron Builder
MIT License
579 stars 108 forks source link

How to listen for webContents.send events from main processes in vue components #42

Closed JasonYHZ closed 1 year ago

JasonYHZ commented 1 year ago

According to the current project, I can easily use contextBridge from the render process to send messages from the vue process to the main process, but conversely, I do not know how to respond to the message events sent by the main process within the life cycle of the main process.

Deluze commented 1 year ago

Hi! I highly suggest you take a look at the IPC tutorial from Electron: https://www.electronjs.org/docs/latest/tutorial/ipc#2-expose-ipcrendereron-via-preload

The link shows you how to subscribe to an event sent through webContents.send from the main process

JasonYHZ commented 1 year ago

Hi! I highly suggest you take a look at the IPC tutorial from Electron: https://www.electronjs.org/docs/latest/tutorial/ipc#2-expose-ipcrendereron-via-preload

The link shows you how to subscribe to an event sent through webContents.send from the main process

The instructions in this document I know that if I follow the document, I can only listen for messages in preloaded scripts and modify DOM directly, but what I really want to solve is how to listen for messages during the life cycle of vue. So that it can update vue UI

image
Deluze commented 1 year ago

Following the example in the docs:

// preload.ts
const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electronAPI', {
    onUpdateCounter: (callback) => ipcRenderer.on('update-counter', callback)
})

You can access your Vue ref's like this:

// App.vue
const msg = ref('');
window.electronAPI.onUpdateCounter((event, count) => msg.value = count.toString());