https://blog.csdn.net/weixin_41549915/article/details/110931264

前言

  • electron:使用 JavaScript,HTML 和 CSS 构建跨平台的桌面应用程序
  • 在之前,通常我们会使用electron-vue脚手架来快速搭建,但是这个脚手架搭建的Electron版本已经太旧了,目前github已经一年没提交更新了,所以我们需要使用其他新的方式来搭建。
  • 本教程使用Vue CLI Electron插件,快速的搭建Electron+Vue项目,关于插件的信息可进入Vue CLI Plugin Electron Builder官网自行了解,下面我们开始搭建

vue项目搭建

  • 使用Vue脚手架创建Vue项目

npm install -g @vue/cli
# OR
yarn global add @vue/cli
  • 创建项目
vue create myproject

配置Electron

  • 首先进入项目目录
cd myproject
  • 然后通过运行以下命令安装并调用vue-cli-plugin-electron-builder的生成器:
vue add electron-builder

如下图所示,提示我们选择Electron版本,直接选择最新9.0.0版本即可

接下来根据您的网络情况,安装时间各异,一般为15-60秒左右,安装成功后如下提示:

启动

yarn electron:serve
//OR
npm run electron:serve

background.js主进程常用配置

  • 主进程的主要作用
1、创建渲染进程
2、管理应用程序的生命周期
3、与系统底层交互
  • 设置渲染进程的大小、外观

win = new BrowserWindow({width: 1200, // 设置窗口的宽height: 620, // 设置窗口的高webPreferences: {webSecurity: false, // 是否禁用浏览器的跨域安全特性nodeIntegration: true // 是否完整支持node}})

此处只设置了几个基本属性,更多属性请参考: https://www.w3cschool.cn/electronmanual/electronmanual-browser-window.html

  • 设置菜单

function createMenu () {// darwin表示macOS,针对macOS的设置if (process.platform === 'darwin') {const template = [{label: 'App Demo',submenu: [{role: 'about'},{role: 'quit'}]}]const menu = Menu.buildFromTemplate(template)Menu.setApplicationMenu(menu)} else {// windows及linux系统Menu.setApplicationMenu(null)}
}

在这里要注意,MacOS和windows及Linux的处理是不一样的

  • 当应用启动后(初始化完成)要做的一些事情
app.on('ready', async () => {if (isDevelopment && !process.env.IS_TEST) {if (isDevelopment && !process.env.IS_TEST) {// Install Vue Devtoolstry {await installVueDevtools()} catch (e) {console.error('Vue Devtools failed to install:', e.toString())}}}globalShortcut.register('CommandOrControl+Shift+i', function () {win.webContents.openDevTools()})createWindow()
})

app模块的ready方法执行完之后就可以创建渲染进程了。该方法默认是如果是开发环境则自动安装VueDevTools方便开发者调试。同时也在全局注册了使用Ctrl + Shift + i 呼出VueDevTool,在设置完这些插件之后,再创建渲染进程。在此处通常做一些应用初始化的工作,例如:提前加载一些数据,等到渲染进程渲染完页面之后直接调用,加快应用加载速度等。

  • 当应用所有窗口关闭要做的事情

app.on('window-all-closed', () => {// On macOS it is common for applications and their menu bar// to stay active until the user quits explicitly with Cmd + Qif (process.platform !== 'darwin') {app.quit()}
})
  • 与渲染进程进行通讯

官方有多种通讯方式,我们这里介绍最常用的一种ipcRenderer(渲染进程中使用的对象)和ipcMain(主进程中使用的对象)。比如渲染进程让主进程关闭当前窗口 渲染进程

const { ipcRenderer } = require('electron')
ipcRenderer.send('close');

主进程

import { ipcMain } from 'electron'
ipcMain.on('close', e => win.close());
  • 如何解决启动或打包缓慢问题
根目录新建.npmrc文件:electron_mirror="https://npm.taobao.org/mirrors/electron/"
electron_builder_binaries_mirror="http://npm.taobao.org/mirrors/electron-builder-binaries/"
  • 动态修改窗口大小

通常很多桌面应用,初次打开都需要登录,登录窗口比较小,登录成功之后展示一个更大的窗口,展示登录后的信息。例如QQ,钉钉,有道云笔记这些应用。

1、修改窗口大小
通常登录窗口比较小,这个我们将登录窗口大小设置为宽:400,高:550 background.jswin = new BrowserWindow({width: 400,height: 550,webPreferences: {nodeIntegration: true}})2、绘制一个登录界面
<template><div class="main"><div class="item"><el-button type="primary" round @click="login">登录</el-button></div></div>
</template>
<script>
export default {name: 'Login',data () {return {account: '',password: ''}},methods: {login () {if (this.account === 'admin' && this.password === '123456') {this.$router.push('Home')} else {this.$message.error('用户名或密码错误')}}}
}
</script>3、进入Home页面后,我们要将窗口的大小,调整为正常窗口大小,我们设置宽:1050,高:700;通过第二篇文章,我们知道改变窗口大小是需要再主进程中才能操作,我们Home页面是渲染进程,所以我们这时候要用到进程间通讯。主进程(background.js)增加以下代码import { app, protocol, BrowserWindow, ipcMain } from 'electron'
ipcMain.on('changWindowSize', e =>win.setSize(1050, 700)
)// Home.vue
<template><div class="home"><img alt="Vue logo" src="../assets/logo.png"></div>
</template>
<script>
const { ipcRenderer } = require('electron')
export default {name: 'Home',mounted () {this.changeWindowSize()},methods: {changeWindowSize () {ipcRenderer.send('changWindowSize')}}
}
</script>
  • 去掉外边框

我们修改background.js,修改createWindow方法,创建BrowserWindow时增加frame: falsewin = new BrowserWindow({width: 400,height: 550,frame: false,webPreferences: {nodeIntegration: true}})
  • 增加操作栏
我们修改Login.vue,增加以下代码const { ipcRenderer } = require('electron')
// 点击最小化按钮调用的方法
minimize () {ipcRenderer.send('minimize')
},
// 点击关闭按钮调用的方法
close () {ipcRenderer.send('close')
},窗口的拖动需要增加以下样式:-webkit-app-region: drag; // 可拖动
-webkit-app-region: no-drag; // 不可拖动主线程中增加对应的最小化和关闭窗口的方法ipcMain.on('close', e =>win.close()
)ipcMain.on('minimize', e =>win.minimize()
)
  •  打开新窗口
// 新建Calendar.vue<template><div><el-calendar v-model="value"></el-calendar></div>
</template><script>
export default {name: 'Calendar',data () {return {value: new Date()}}
}
</script>// 修改router{path: '/Calendar',name: 'Calendar',component: Calendar
}// 修改background.js
(这段代码主要是用来解决vue路由访问页面的问题,端口号是vue启动的默认端口号,如果有需要可以自行修改)const winURL = process.env.NODE_ENV === 'development'? 'http://localhost:8080': `file://${__dirname}/index.html`win.loadURL(winURL)(这段代码主要是修改主窗口加载的url,修改我我们上边声明的那个)=================================================================================// 定义calendar窗体
这段代码是打开新窗口的代码,calendarWin.loadURL(winURL + '#/Calendar') 是指向我们上边创建的页面。let calendarWin
// 创建calendar窗口方法
function openCalendarWindow () {calendarWin = new BrowserWindow({width: 400,height: 550,parent: win, // win是主窗口webPreferences: {nodeIntegration: true}})calendarWin.loadURL(winURL + '#/Calendar')calendarWin.on('closed', () => { calendarWin = null })
}
ipcMain.on('openCalendarWindow', e =>openCalendarWindow()
)// 在Home.vue页面中调用创建新窗口的方法
openCalendarWindow () {ipcRenderer.send('openCalendarWindow')
}

打包

  • 设置应用appId
在package.json 中增加"appId": "com.ipp.electronvue",
  •  增加vue.config.js
这个文件是用来配置打包工具electron-builder的参数,代码中有对应的注释,按照对应的配置修改为自己的图标就好。module.exports = {// 第三方插件配置pluginOptions: {// vue-cli-plugin-electron-builder 配置electronBuilder: {builderOptions: {// 设置打包之后的应用名称productName: 'electron-vue-demos',win: {icon: 'public/electron-icon/icon.ico',// 图标路径 windows系统中icon需要256*256的ico格式图片,更换应用图标亦在此处target: [{// 打包成一个独立的 exe 安装程序target: 'nsis',// 这个意思是打出来32 bit + 64 bit的包,但是要注意:这样打包出来的安装包体积比较大arch: ['x64'// 'ia32']}]},dmg: {contents: [{x: 410,y: 150,type: 'link',path: '/Applications'},{x: 130,y: 150,type: 'file'}]},linux: {// 设置linux的图标icon: 'resources/ico/icon.png',target: 'AppImage'},mac: {icon: 'resources/ico/icon.icns'},files: ['**/*'],extraResources: {// 拷贝dll等静态文件到指定位置,否则打包之后回出现找不大dll的问题from: 'resources/',to: './'},asar: false,nsis: {// 是否一键安装,建议为 false,可以让用户点击下一步、下一步、下一步的形式安装程序,如果为true,当用户双击构建好的程序,自动安装程序并打开,即:一键安装(one-click installer)oneClick: false,// 允许请求提升。 如果为false,则用户必须使用提升的权限重新启动安装程序。allowElevation: true,// 允许修改安装目录,建议为 true,是否允许用户改变安装目录,默认是不允许allowToChangeInstallationDirectory: true,// 安装图标installerIcon: 'resources/ico/icon.ico',// 卸载图标uninstallerIcon: 'resources/ico/icon.ico',// 安装时头部图标installerHeaderIcon: 'resources/ico/icon.ico',// 创建桌面图标createDesktopShortcut: true,// 创建开始菜单图标createStartMenuShortcut: true}},chainWebpackMainProcess: config => {config.plugin('define').tap(args => {args[0].IS_ELECTRON = truereturn args})},chainWebpackRendererProcess: config => {config.plugin('define').tap(args => {args[0].IS_ELECTRON = truereturn args})}}}
}
  •  执行打包命令
npm run electron:build

动态设置IP

  • 下载electron-store
npm run electron-store -S
  •  background.js
const Store = require('electron-store')
const store = new Store({ encryptionKey: 'jsdyt' })
global.dytStore = store
  • main.js 
let flag = window && window.process && window.process.versions && window.process.versions['electron']if (flag) {const { remote } = window.require('electron')Vue.prototype.dytStore = remote.getGlobal('dytStore')
}
  •  setting.js(设置常用变量baseUrl等)
let flag = window && window.process && window.process.versions && window.process.versions['electron']
let baseUrl = ''
let picSrc = ''
if (flag) {const { remote } = window.require('electron')const dytStore = remote.getGlobal('dytStore')baseUrl =process.env.NODE_ENV === 'development' ? process.env.VUE_APP_API : 'http://' + dytStore.get('serverIp') + '/' + process.env.VUE_APP_APIpicSrc = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_IMGSRC : 'http://' + dytStore.get('serverIp') + '/nas'
} else {baseUrl = process.env.VUE_APP_APIpicSrc = process.env.VUE_APP_IMGSRC
}export default {baseUrl,flag // 判断是否是electron
}
  •  base.js(axios请求封装)
import setting from '../setting'service.defaults.baseURL = setting.baseUrl

启动外部exe系统

// vue.config.jsbuilderOptions: {extraResources: { // 拷贝dll等静态文件到指定位置from: './public/DytTool', // 将需要被打开的系统放到指定位置to: './DytTool' // 打包后的系统位置}
}// 打开openHandle() {const { exec } = window.require('child_process')exec('start .\\resources\\DytTool\\DytTool.exe')
},============ 最新方式 =============// background.js标注:以启动签拍机为例let dytToolPath = null
const isDevelopment = process.env.NODE_ENV != 'production'if(isDevelopment){
// 开发环境dytToolPath = path.resolve(__dirname, '../DytTool/DytTool.exe') // 签拍机(这个路径是指当前第三方程序放在项目中位置)
}else{dytToolPath = path.resolve(__dirname, '../DytToolResources/DytTool.exe') // 签拍机(这个路径是指打包后程序存在的位置)
}// 返回签拍机路径ipcMain.on('open::dytTool', async event => {event.returnValue = dytToolPath
})// vue.config.jspluginOptions:{electronBuilder: {extraResources: [{from: './DytTool', // 签拍机to: './DytToolResources'}]}
}// 组件中使用/**打开签拍机 */openHandle() {let path = ipcRenderer.sendSync('open::dytTool')exec(`\"${path}\"`, (error, str, err) => {console.log(error)console.log(str)console.log(err)})
}/**杀掉签拍机的进程*/exec(`taskkill /f /t /im DytTool.exe`, (error, stdout, stderr) => {})

下载文件

// 下载downLoad(row) {const { remote } = window.require('electron')const fs = require('fs')const path = require('path')let that = thisvar extname = path.extname(row.resPath).split('.')[1]console.log(extname)remote.dialog.showSaveDialog({defaultPath: path.basename(row.originalName),title: '保存文件',filters: [{ name: 'Custom File Type', extensions: [extname] }]}).then(response => {http.get(row.resPath, res => {var imgData = ''res.setEncoding('binary') //一定要设置response的编码为binary否则会下载下来的图片打不开res.on('data', chunk => {imgData += chunk})res.on('end', () => {fs.writeFile(response.filePath, imgData, 'binary', function (err) {if (err) {console.log('down fail')} else {that.$message.success('保存成功')}})})})})
}

错误总结

1.Electron-vue报错Webpack ReferenceError:process is not defined解决:修改.electron-vue/webpack.web.config.js和.electron-vue/webpack.renderer.config.js文件的HtmlWebpackPlugin,添加templateParameters,修改后如下:new HtmlWebpackPlugin({filename: 'index.html',template: path.resolve(__dirname, '../src/index.ejs'),templateParameters(compilation, assets, options) {return {compilation: compilation,webpack: compilation.getStats().toJson(),webpackConfig: compilation.options,htmlWebpackPlugin: {files: assets,options: options},process,};},minify: {collapseWhitespace: true,removeAttributeQuotes: true,removeComments: true},nodeModules: false}),
electron不支持cookies,这在设置token时,会拿不到token值。使用window.localstorage.getItem()

手牵手系列之搭建Vue+Electron项目相关推荐

  1. 快速简洁的Vue+Electron项目搭建教程

    Vue+Electron项目搭建教程 最近写一个项目,需要使用Electron集成Vue,特此记录搭建过程 Vue+Electron 常用搭建方式 在之前,通常我们会使用electron-vue脚手架 ...

  2. VUE项目学习(一):搭建VUE前端项目

    VUE项目学习(一):搭建VUE前端项目 1.安装node.js环境 (1)下载node.js,下载地址为:https://nodejs.org/en/ (2)按照默认选项安装node,检查安装版本 ...

  3. cmd搭建vue前端项目详细过程

    cmd 搭建vue前端项目 下载nods.js node.js下载(Windows版本) next 安装完毕! 配置node.js环境变量 进入找到Path进入 这里填你的node.js的安装路径 验 ...

  4. 基于vue-cli搭建VUE.js项目

    基于vue-cli搭建VUE.js项目 准备工作 开始安装 搭建工程 目录结构 搞定!! 准备工作 1.node.js 2.vue-cli 3.webpack 开始安装 Node.js 点击去下载No ...

  5. 手牵手系列之TypeScript开发环境搭建

    新建项目 初始化 npm init 安装全局依赖 npm install typescript tslint -g 执行命令初始化,项目根目录生成tsconfig.json文件 tsc --init ...

  6. Vue + Spring Boot 项目实战(二):使用 CLI 搭建 Vue.js 项目

    文章目录 一.安装 Vue CLI 二.构建前端项目 2.1.创建一个基于 webpack 模板的项目 2.2. 安装图解 2.3. 项目结构总览 2.4. 运行项目 2.5. 浏览器验证 项目Git ...

  7. 使用mac搭建vue脚手架项目

    1.  需要安装Node.js C:\Users\wheat> node -v v8.9.3 C:\users\wheat> npm -v 2. 安装vue 脚手架 用cnpm(使用国内镜 ...

  8. linux系统下docker搭建vue前端项目开发运行环境详解

    1. 初衷 最近做了几个前后端项目,在前后端项目链条的时候,发现在windows系统下安装前端发过来的vue项目的依赖的时候各种报错, npm install一直无法安装,但是我在linux系统下面安 ...

  9. 三种方式快速搭建vue环境项目全过程(图解)

    (一)环境搭建 1.下载源码 如果仅仅只是在项目或者某个文件中简单的使用vue,就可以直接在html中引入下列链接 <script src="https://unpkg.com/vue ...

最新文章

  1. 计算机缺失缺少mfc110.dll等相关文件的解决办法
  2. Django静态文件一瞥
  3. java 判断类型_如何快速入门Java编程学习(干货)
  4. eclipse下使用maven配置库托管jar包
  5. 电脑下载的M4A格式文件怎么转换为MP3格式
  6. MSFT Outlook VBA处理新邮件的方法
  7. javasript 面向对象
  8. 关于判断函数凸或凹以及最优化的问题
  9. html5前端实习招聘面试,2018头条春招前端实习生面试题目总结
  10. 【小型JavaFx项目】文字小冒险游戏
  11. Eclipse代码自动补全设置
  12. 关于光模块用单模光纤和多模光纤小知识
  13. 安卓车机数字时间屏保
  14. VMI - 供应商管理库存
  15. 京东联盟自动转链php,求京东联盟php自动转链源码 请 ZenHaBit 继续帮忙
  16. python五子棋课程设计报告_算法课程设计:使用Python完成可视化的五子棋AI
  17. 用echarts实现水滴图效果
  18. SLAM数据集、RGB-D数据集
  19. 已解决(Python安装报错)Visit python.org to download an earlier version of Python.
  20. 关于原创文章特此说明

热门文章

  1. TMMI_测试过程改进框架
  2. Redis 主从搭建
  3. Python | 自动生成表情包,从此斗图无敌手!
  4. shellcode事件
  5. 满足用户的即时需求,金融云的效率优先与生态开放
  6. linux如何调出xfce4,Archlinux+xfce4安装完成后配置
  7. 基于星环科技大数据平台 辽宁城市建设职业技术学院打造智慧校园
  8. emqttd配置_emqttd学习教程(一):emqttd安装与部署-Go语言中文社区
  9. 【JVM我可以讲一个小时】
  10. pytorch之Softmax回归