使用electron-vite创建桌面应用

使用electron-vite创建桌面应用

一、框架搭建

官网地址https://cn.electron-vite.org

bash 复制代码
npm create @quick-start/electron@latest

按步骤操作即可

二、项目目录

1、main 主进程窗口:存放窗口代码

2、preload 预加载模块:用于窗口与页面间沟通的桥梁,增加可靠性

3、renderer渲染模块:主要存放前端页面代码

三、preload.js解读

官网对应位置:https://www.electronjs.org/zh/docs/latest/api/context-bridge

1、在preload/index.js中定义预加载信息

bash 复制代码
import { contextBridge,ipcRenderer } from 'electron'
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('mytest', {
       //当前方法可以在渲染模块通过 window.mytest.doThing 进行调用
        doThing: () => ipcRenderer.send('mqtt_data')
    })
  } catch (error) {
    console.error(error)
  }
} else {
  window.mytest= {
       //兼容问题
        doThing: () => ipcRenderer.send('mqtt_data')
    }
}

2、在渲染模块中进行调用

bash 复制代码
<script setup>
    function handleClick() {
       window.mytest.doThing()
    }
</script>

<template>
  <ul class="versions">
    <button @click="handleClick">按钮</button>
  </ul>
</template>

3、在主进程中进行接收

bash 复制代码
import { ipcMain } from 'electron'
ipcMain.on('mqtt_data', () => console.log(666))

效果:

相关推荐
Wetoria8 分钟前
管理 git 分支时,用 merge 还是 rebase?
前端·git
前端开发与ui设计的老司机18 分钟前
UI前端与数字孪生融合新领域:智慧环保的污染源监测与治理
前端·ui
一只小风华~32 分钟前
Web前端开发: :has功能性伪类选择器
前端·html·html5·web
成遇39 分钟前
Eslint基础使用
javascript·typescript·es6
Mr_Mao5 小时前
Naive Ultra:中后台 Naive UI 增强组件库
前端
前端小趴菜056 小时前
React-React.memo-props比较机制
前端·javascript·react.js
摸鱼仙人~7 小时前
styled-components:现代React样式解决方案
前端·react.js·前端框架
sasaraku.8 小时前
serviceWorker缓存资源
前端
RadiumAg9 小时前
记一道有趣的面试题
前端·javascript
yangzhi_emo9 小时前
ES6笔记2
开发语言·前端·javascript