Electron+vue3+vue-router搭建跨平台桌面应用程序

electron-vue
vue3
electron快速入门
1、创建vue项目

vue create vue-electron

2、添加electron

vue add  electron-builder

可能会卡顿或者下载不了,改变一下electron的镜源

vi ~/.npmrc

添加:

electron_mirror=https://npm.taobao.org/mirrors/electron/

看一下package.json
请添加图片描述
新建background.js文件,package.json中配置。
请添加图片描述
background.js中配置窗口的基本信息

import { app, protocol, BrowserWindow } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      enableRemoteModule: true,
    }
  })
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (isDevelopment) {
      win.webContents.openDevTools()
    }
  } else {
    createProtocol('app')
    win.loadURL('app://./index.html')
  }
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
  }
  createWindow()
})
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

//打包
 npm run electron:build
//调试/开发
 npm run electron:serve
//用于在安装应用程序依赖时执行 electron-builder install-app-deps 命令,以确保安装的依赖包含必要的二进制文件
 npm run postinstall

npm run electron:build会自动识别当前的操作系统,打出系统对应的安装包。 这也意味着,如果要生成exe\msi,需要在Windows操作系统,如果是dmg,则需要在Mac操作系统。
请添加图片描述

npm run electron:build 打包失败
1、项目路径中不能包含中文!!!!
2、先npm run build 再npm run electron:build

3、添加路由vue-router

npm install vue-router

新建router/index.js文件
1、使用createWebHashHistory,为什么呢?因为使用createWebHistory打包后跳转的路由空白。没研究出来为啥,有知道的可评论一下告诉我,感谢~

import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
  {
    path: '/homePage',
    name: "homePage",
    meta: {
      title: "首页"
    },
    component: () => import('@/views/homePage.vue')
  },
  { path: '/', redirect: '/homePage' },
  { path: '/:pathMatch(.*)', 
  component: () => import('@/views/homePage.vue')
  },
  {
    path: '/mdProtocol',
    meta: {
      title: "订阅合约"
    },
    name: 'mdProtocol',
    component: () => import('@/views/mdProtocol.vue')
  },
]

const router = createRouter({
  history: createWebHashHistory(), 
  routes
})

router.beforeEach((to, form, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next()
})

export default router

2、设置路由中的tittle,这是窗口的自定义标题,如果不使用路由,那使用

win.setTitle('标题')

3、main.js 中引入router

import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router/index'
createApp(App).use(router).mount('#app')

4、app.vue中
请添加图片描述

4、打开多个窗口
使用ipcMain监听和ipcRenderer通知
在background.js文件中添加ipcMain。因为路由使用的hash模式,所以要注意win.loadURL中的要加上#哦,如下:

win.loadURL(winURL + '#' + data.filePath)

所有的代码如下:

import { app, protocol, BrowserWindow, ipcMain } from 'electron'
const isDevelopment = process.env.NODE_ENV !== 'production'
const winURL = isDevelopment ? process.env.WEBPACK_DEV_SERVER_URL : `file://${__dirname}/index.html/`
ipcMain.on('create-window', (e, data) => {
  console.log('file', data.filePath)
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      enableRemoteModule: true,
      // webSecurity: false
    },
  })
  
  win.loadURL(winURL + '#' + data.filePath)
  if (!process.env.IS_TEST) win.webContents.openDevTools()
})

在需要打开多窗口多页面使用ipcRenderer

<script setup>
const { ipcRenderer } = require('electron')
function openWin() {
  ipcRenderer.send('create-window', { filePath: "mdProtocol" })
}
function openWin2() {
  ipcRenderer.send('create-window', { filePath: "tdProtocol" })
}
</script>

效果如下:

请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先需要安装一些依赖: ```bash npm install electron electron-context-menu vite vue@next vue-router@next @vue/compiler-sfc typescript tslib --save-dev ``` 然后在 `src` 目录下新建 `main.ts` 和 `renderer.ts` 两个文件。 `main.ts` 的内容如下: ```ts import { app, BrowserWindow, Menu } from 'electron'; import path from 'path'; import contextMenu from 'electron-context-menu'; // 创建窗口 function createWindow() { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { // 允许使用 node.js nodeIntegration: true, // 允许使用 Electron 的 remote 模块 enableRemoteModule: true, // 允许在渲染进程中使用上下文菜单 contextIsolation: false, }, }); // 加载页面 win.loadFile(path.join(__dirname, '../renderer/index.html')); // 打开开发者工具 win.webContents.openDevTools(); // 设置窗口菜单 const template = [ { label: '菜单1', submenu: [ { label: '子菜单1', click: () => { console.log('点击了子菜单1'); }, }, { label: '子菜单2', click: () => { console.log('点击了子菜单2'); }, }, ], }, { label: '菜单2', click: () => { console.log('点击了菜单2'); }, }, ]; const menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); } // 当 Electron 初始化完成并准备好创建窗口时调用这个函数 app.whenReady().then(() => { // 注册上下文菜单 contextMenu({ window: BrowserWindow.getFocusedWindow(), showInspectElement: true, }); createWindow(); // 如果所有窗口都关闭了,退出应用 app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); }); // 在 macOS 上,当单击 Dock 图标并且没有其他窗口打开时,重新创建一个窗口 app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } }); ``` `renderer.ts` 的内容如下: ```ts import { createApp } from 'vue'; import App from './App.vue'; createApp(App).mount('#app'); ``` 接下来在 `src` 目录下新建 `index.html` 文件,并且在里面添加一个 `div` 元素,并且指定它的 `id` 为 `app`。同时在 `body` 元素下添加如下代码: ```html <script src="./renderer.js"></script> ``` 最后在 `package.json` 中添加如下脚本: ```json { "scripts": { "start": "vite", "build": "vite build", "electron": "electron ." } } ``` 现在可以运行 `npm run start` 来启动应用程序,然后运行 `npm run electron` 来启动 Electron 应用程序。现在你应该已经能够看到一个 Electron 窗口,并且它包含一个菜单。如果你右键单击窗口,你应该能够看到一个上下文菜单。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值