electron+vue+ts窗口间通信

这篇具有很好参考价值的文章主要介绍了electron+vue+ts窗口间通信。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


    "@types/node": "^20.3.1",
    "@vitejs/plugin-vue": "^4.1.0",
    "@vueuse/electron": "^10.2.1",
    "electron": "^25.2.0",
    "electron-packager": "^17.1.1",
    "typescript": "^5.0.2",
    "vite": "^4.3.9",
    "vue-tsc": "^1.4.2"

一. 目的

现有场景: 用户点击图,在新窗口展示实时数据
electron+vue+ts窗口间通信,electron,vue.js,javascript
electron+vue+ts窗口间通信,electron,vue.js,javascript


二.逻辑分析

vue作为纯渲染线程不具备操作本地数据以及窗口间通讯的功能,必须由经electron主进程解决.
因此官方为我们提供了IpcRederer向主进程发送消息的能力. 以及IpcMain主进程监听处理消息的能力.

由于ts和electron上下文隔离策略限制不允许直接使用request读取IpcRederer对象. 我们可以借助 usevue vue的第三方集成api综合库.读取ipcRederer

因此请注意
在vue渲染线程中 我们要参考的是usevue的官方文档 —> usevue
在electron主进程参考 —> electron

  1. 用户点击图谱
  2. A窗口向主进程发送打开B窗口请求
  3. 主进程收到A窗口消息, 创建B窗口.返回响应
  4. A窗口接收响应, 向生产者信道发送数据
  5. 主进程监听生产者信道接收数据,主进程将监听消息发送给消费者信道
  6. B窗口读取消费者信道数据

electron+vue+ts窗口间通信,electron,vue.js,javascript


三. 代码示例

A.vue

import {useIpcRenderer} from "@vueuse/electron";
const ipcRenderer = useIpcRenderer();

async function openTextBox() {
    await res.open()
    console.log(res.data.value)
    // 向发送数据
    resp.value = ipcRenderer.invoke('product-msg', res.data.value)
    if(resp.value){
        // 创建新窗口
        ipcRenderer.send('textBox', '/browse')
        resp.value=false
    }
}

Main.js/Main.ts 主进程

// Modules to control application life and create native browser window

const { app, BrowserWindow, ipcMain,Menu } = require('electron')
// import './src/store/index'
const path = require('path')
// const winURL = process.env.NODE_ENV === 'development' ? 'http://localhost:8080' : `file://${path.join(__dirname, './dist/index.html')}`

let mainWindow
let textdata
let atlasdata
let textBox;
function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        width: 1280,
        height: 1024,
        minWidth: 600,
        minHeight: 600,
        title: '局部放电监控中心',
        // autoHideMenuBar: true, // 自动隐藏菜单栏
        webPreferences: {
            // 是否启用Node integration
            nodeIntegration: true, // Electron 5.0.0 版本之后它将被默认false
            // 是否在独立 JavaScript 环境中运行 Electron API和指定的preload 脚本.默认为 true
            contextIsolation: false,  // Electron 12 版本之后它将被默认true
            nodeIntegrationInWorker: true,
            // 禁用同源策略,允许跨域
            webSecurity: false,
            preload: path.join(__dirname, 'preload.js'),

        }

    })
  

    // and load the index.html of the app.
    // 访问路径,需要配合路由转发到vue页面
    mainWindow.loadFile('./dist/index.html')
    // Open the DevTools.
    mainWindow.webContents.openDevTools({mode:'right'})

    // 监听窗口关闭
    mainWindow.on('window-close', function () {
        mainWindow.close();
    })
    // 主进程上下文渲染时机  did-finish-load 窗口导航栏渲染完成触发
    mainWindow.webContents.on('did-finish-load', () => {
        console.log("主进程渲染,主窗口加载完毕")
      })

}

// 左上角导航菜单栏
const menu = Menu.buildFromTemplate([
    {
      label: app.name,
      submenu: [
        {
          click: () => textBox.webContents.send('customer-msg', textdata),
          label: 'Increment'
        },
      ]
    }
  ])
Menu.setApplicationMenu(menu)
  

// 监听textBox消息
ipcMain.on('textBox', function (event, data) {
    console.log("接收")
    textBox = new BrowserWindow({
        width: 1280,
        height: 1024,
        minWidth: 600,
        minHeight: 600,
        parent: mainWindow, // mainWindow是主窗口
        frame: true, // 有边框
        title: '查看',
        autoHideMenuBar: true, // 自动隐藏菜单栏
        webPreferences: {
            // 是否启用Node integration
            nodeIntegration: true, // Electron 5.0.0 版本之后它将被默认false
            // 是否在独立 JavaScript 环境中运行 Electron API和指定的preload 脚本.默认为 true
            contextIsolation: false,  // Electron 12 版本之后它将被默认true
            nodeIntegrationInWorker: true,
            // 禁用同源策略,允许跨域
            webSecurity: false,
            preload: path.join(__dirname, 'preload.js'),
        }
    })
    // console.log(data,"---2323---")
    // textBox.loadURL('http://127.0.0.1:3000/#/add')  // 此处写 你要打开的路由地址
    textBox.loadFile('./dist/index.html', {
        hash: '#' + data
    });
    // 监听textBox窗口关闭
    textBox.on('closed', () => {
        textBox == null;
    })
    // Open the DevTools.
    textBox.webContents.openDevTools({ mode: 'right' })
    // textBox.webContents.on('did-finish-load', () => {
    //     console.log("渲染进程渲染,新窗口加载完毕")
    //     textBox.webContents.send('customer-msg', textdata)
    //   })
    // did-stop-loading 打开新窗口触发3次, 关闭触发1次
    textBox.webContents.on('did-stop-loading', () => {
        console.log("渲染进程渲染,新窗口加载完毕")
        textBox.webContents.send('customer-msg', textdata)
        textBox.webContents.send('atlas-customer-msg', atlasdata)
    })
})

// 监听 product-msg 信道消息
ipcMain.handle('product-msg', async (event, data) =>{
    console.log(data, "i am data")
    textdata = data
    return true;
});
ipcMain.handle('atlas-msg', async (event, data) =>{
    console.log(data, "i am atlas")
    atlasdata = data
    return true;
});




// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow)

    app.on('activate', function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })


// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

B.vue文章来源地址https://www.toymoban.com/news/detail-631030.html

<template>
    <span>{{ data }}</span>
</template>

<script setup lang="ts">
import { ref} from "vue";
import {useIpcRenderer} from "@vueuse/electron";

const ipcRenderer = useIpcRenderer();

const data = ref('')
    ipcRenderer.on('customer-msg', ((event, arg) => {
        data.value = arg;
        console.log(arg)    
    }))
</script>


<style></style>

到了这里,关于electron+vue+ts窗口间通信的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用Electron + Vue3 + TS搭建桌面端应用并可热更新

    以下是必要的技术: Electron 13.0.0 Vue3 + TS Electron-updater Node 16.13.1 Element-plus Less Meansjs 安装Vue-cli(如果未安装): npm install -g @vue/cli 创建Vue3项目: vue create electron-vue3 启动项目: yarn serve 安装Electron: vue add electron-builder 启动项目: yarn electron:serve 如果报错,需要安装ts-loader: yar

    2023年04月26日
    浏览(75)
  • 基于electron25+vite4创建多窗口|vue3+electron25新开模态窗体

    在写这篇文章的时候,查看了下electron最新稳定版本由几天前24.4.0升级到了25了,不得不说electron团队迭代速度之快! 前几天有分享一篇electron24整合vite4全家桶技术构建桌面端vue3应用示例程序。 https://www.cnblogs.com/xiaoyan2017/p/17436076.html 这次继续接着上次项目,主要介绍electron

    2024年02月06日
    浏览(67)
  • Vite + Vue3 + Electron实现进程通信

    Electron 是一个基于 Chromium 和 Node.js 的桌面应用程序开发框架,而 Vue3 则是一种流行的前端框架。将两者结合使用可以快速地打造出跨平台的桌面应用程序。在这种组合中,Electron 提供了强大的桌面应用开发能力,而 Vue3 则提供了易用的 UI 组件和开发体验 Electron 内置了 Chrom

    2024年02月12日
    浏览(38)
  • Vue3 - 实现路由 “新开一页“ 进行页面跳转功能,Router 路由跳转时在新窗口打开页面(网站跳转页面时浏览器新开页签打开网页,支持在页面、纯 js/ts 文件中使用,详细示例代码教程)

    网上这方面教程很少,本文提供多种解决方案,适用于任何场景。 本文 实现了在 vue3 项目开发中,当页面跳转时浏览器打开新窗口(新页签)跳转,Router 路由跳转并新开一页教程, 无论您是在普通页面、纯 js/ts 文件中,都可以使用, 如下图所示,当执行路由跳转时浏览器

    2024年02月03日
    浏览(48)
  • electron+vue3全家桶+vite项目搭建【16.1】electron多窗口,pinia状态同步,扩展store方法,主动同步pinia的状态【推荐】

    demo项目地址 我们之前写了一个自动同步pinia状态的插件,可以参考如下文章 electron+vue3全家桶+vite项目搭建【16】electron多窗口,pinia状态无法同步更新问题解决 这里面有一个较大的弊端,就是pinia中的store,只要其中的某个属性修改,就会触发这个store的全量更新,当我们有一

    2024年02月11日
    浏览(54)
  • js(javascript)中页面跳转和窗口关闭等操作

    1、self.loaction.href=\\\"/具体路径\\\" 2、location.href=\\\"/具体路径\\\" 3、windows.loaction.href=\\\"/具体路径\\\" 4、this.loaction.href=\\\"/具体路径\\\" parent.location.href=\\\"/具体路径\\\" top.location.href=\\\"/具体页面\\\" window.location.reload() 使用该方法刷新页面时,如果有数据待提交,会提示是否提交 如果页面中自定义了f

    2024年02月16日
    浏览(36)
  • 使用vue3+vite+elctron构建小项目介绍Electron进程间通信

    进程间通信 (IPC) 是在 Electron 中构建功能丰富的桌面应用程序的关键部分之一。 由于主进程和渲染器进程在 Electron 的进程模型具有不同的职责,因此 IPC 是执行许多常见任务的唯一方法,例如从 UI 调用原生 API 或从原生菜单触发 Web 内容的更改。 在 Electron 中,进程使用 ipcM

    2024年02月06日
    浏览(41)
  • VUE3+TS(父子、兄弟组件通信)

    目录 父传子值、方法(子调用父值、方法) 子传父值(父调用子值) 父读子(子传父)(父调用子值、方法) 兄弟(任意组件)通信 引入Mitt来完成任意组件通信 1、统一规范写法,通过在子组件标签上绑定属性和值,来传递到子组件,子组件再通过defineProps来接收,先给其

    2023年04月08日
    浏览(37)
  • vue中electron与vue通信(fs.existsSync is not a function解决方案)

    dist/main.js (整个文件配置在另一条博客里) vue文件中 vue文件中 dist/main.js (整个文件配置在另一条博客里) 需要注意,在浏览器中运行会报错,需要vue打包后,在dist目录中,运行到exe端才能正常调试

    2024年02月08日
    浏览(28)
  • Vue.js + Electron 的跨平台桌面应用程序开发

    本文介绍了 Vue.js 和 Electron 的基本特点和原理,并分析了它们在桌面应用程序开发中的优势和应用场景。在基于 Vue.js 和 Electron 的桌面应用程序开发实践中,本文详细介绍了项目的搭建和配置,包括环境的准备、项目的初始化和依赖的安装等步骤。然后,本文介绍了使用 Vu

    2024年02月13日
    浏览(56)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包