vue+electron项目,对软件进行配置,包括打包图标、名称等;自定义窗口最小化、全屏、退出软件、界面信息传递等
打包配置
在vue.config.js文件中
// vue.config.js默认配置
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true
})
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
pluginOptions: {
electronBuilder: {
externals: ['my-native-dep'],
nodeModulesPath: ['./node_modules'],
builderOptions: {
appId: "electron.test.com",
productName: "ElectronTest",//项目名,也是生成的安装文件名,即aDemo.exe
copyright: "Copyright © 2022",//版权信息
directories: {
output: "./dist_electron" // 输出文件路径
},
dmg: {
contents: [
{
x: 410,
y: 150,
type: "link",
path: "/Applications"
},
{
x: 130,
y: 150,
type: "file"
}
]
},
mac: {
icon: "./public/icon.icns"
},
win: {//win相关配置
icon: "./public/icon.ico", // 图标,当前图标在根目录下,注意这里有两个坑
target: [
{
target: "nsis", // 利用nsis制作安装程序
arch: [
// "x64", // 64位
"ia32" // 64位
]
}
]
},
linux: {
icon: "./public"
},
nsis: {
oneClick: false, // 是否一键安装
allowElevation: true, // 允许请求提升。 如果为false,则用户必须使用提升的权限重新启动安装程序。
allowToChangeInstallationDirectory: true, // 允许修改安装目录
installerIcon: "./public/icon.ico",// 安装图标
uninstallerIcon: "./public/icon.ico",//卸载图标
installerHeaderIcon: "./public/icon.ico", // 安装时头部图标
createDesktopShortcut: true // 创建桌面图标
}
}
}
}
})
在/public文件夹下,添加图片:icon.icns、icon.ico、icon.png。图片大小有限制,linux使用png图片,大小为 256 * 256。
注意:mac与windows打包后安装,会生成启动图标,linux需要手动自定义。且linux可以选择 linux-unpacked 文件夹下的内容,打包成 deb 包。
终端输入:npm run electron:build
界面配置
窗口配置
软件默认运行的效果如下:
background.js
'use strict'
import { app, protocol, BrowserWindow } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'
// Scheme must be registered before the app is ready
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
}
})
if (process.env.WEBPACK_DEV_SERVER_URL) {
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
}
// Quit when all windows are closed.
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 + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// 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()
})
// 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.on('ready', async () => {
createWindow()
})
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === 'win32') {
process.on('message', (data) => {
if (data === 'graceful-exit') {
app.quit()
}
})
} else {
process.on('SIGTERM', () => {
app.quit()
})
}
}
// 防止debug调试
const runWithDebug = process.argv.find(e => e.includes('--inspect') || e.includes('--inspect-brk') || e.includes('--remote-debugging-port'))
if(runWithDebug){
// 直接退出。
app.quit()
}
对窗口进行配置,改变窗口大小、背景色等,需要在createWindow函数方法中进行设置
async function createWindow () {
let size = screen.getPrimaryDisplay().workAreaSize
const win = new BrowserWindow({
title: 'ElectronTest',
width: size.width, // 设置打开的窗口宽度,此处设置全屏
height: size.height, // 设置打开的窗口高度
minWidth: 1600,
minHeight: 800,
icon: path.join(__static, 'icon.png'),
useContentSize: true,
autoHideMenuBar: true, // 隐藏菜单栏,由于项目中菜单栏一般用不到,此处隐藏
resizable: true, // 窗口大小是否可调整,允许调整窗口大小,最小不能小于上面设置的minWidth、minHeight
backgroundColor: '#000000', // 窗口颜色
frame: false, // 隐藏顶部栏,项目中,顶部栏,一般会进行自定义设置UI,比如放大、缩小、退出等按钮功能
webPreferences: {
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION, // 添加node环境
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
}
})
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 (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
}
效果如下:
自定义顶部栏
此处用到了svg,故需要安装svg-sprite-loader,终端键入:npm install svg-sprite-loader --save-dev
vue.config.js中添加:
chainWebpack(config) {
// 配置svg
const svgRule = config.module.rule('svg')
/**
* vue-cli5特有
*/
svgRule.delete('generator')
svgRule.delete('type')
svgRule.uses.clear()
svgRule
.test(/\.svg$/)
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
}
在/src/components下创建SvgIcon/index.vue
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName"></use>
</svg>
</template>
<script>
export default {
name: 'svg-icon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String
}
},
computed: {
iconName () {
return `#icon-${this.iconClass}`
},
svgClass () {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
/src/icons/svg文件夹下,放入需要用到的图标,在/src/icons/index.js中写入
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg组件
// register globally
Vue.component('svg-icon', SvgIcon)
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)
main.js中引入
import '@/icons' // icon
重启软件
设置App.vue
<template>
<div id="app" class="hei100">
<div class="flex justify_content_end align_items_center menu-box">
<div class="menu-title center_left_right">{{appName}}</div>
<!-- 最小化 -->
<div class="svg-icon minmizable" @click.stop="menuClick('minmizable')">一</div>
<!-- 全屏/非全屏 -->
<div class="ml20 resizable" @click.stop="menuClick('resizable')"><svg-icon :icon-class="resizable ? 'zuixiaohua' : 'zuidahua'"></svg-icon></div>
<!-- 退出软件 -->
<div class="ml20 quit" @click.stop="menuClick('quit')"><svg-icon icon-class="guanbi"></svg-icon></div>
</div>
<router-view />
</div>
</template>
<script>
// import { mapGetters } from 'vuex'
export default {
name: 'App',
data () {
return {
resizable: true,
appName: 'ElectronTest'
}
},
computed: {
// appName最好保存在store中,方便存取
// ...mapGetters([
// 'appName'
// ])
},
methods: {
menuClick (type) {
console.log(type)
}
}
}
</script>
<style lang="scss">
* {
padding: 0;
margin: 0;
}
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
a {
font-weight: bold;
color: #2c3e50;
&.router-link-exact-active {
color: #42b983;
}
}
}
</style>
<style lang="scss" scoped>
.menu-box {
height: 38px;
background: #232729;
position: relative;
color: #95A2AB;
font-size: 20px;
padding: 0 15px;
-webkit-app-region: drag;
.svg-icon {
font-size: 16px;
cursor: pointer;
-webkit-app-region: no-drag;
}
}
/* flex布局兼容写法 start */
.flex {
display: -webkit-box; /* Chrome 4+, Safari 3.1, iOS Safari 3.2+ */
display: -moz-box; /* Firefox 17- */
display: -webkit-flex; /* Chrome 21+, Safari 6.1+, iOS Safari 7+, Opera 15/16 */
display: -moz-flex; /* Firefox 18+ */
display: -ms-flexbox; /* IE 10 */
display: flex; /* Chrome 29+, Firefox 22+, IE 11+, Opera 12.1/17/18, Android 4.4+ */
}
/* 主轴end对齐 */
.justify_content_end {
-webkit-box-pack: end;
-moz-justify-content: flex-end;
-webkit-justify-content: flex-end;
justify-content: flex-end;
}
/* 侧轴居中 */
.align_items_center{
-webkit-box-align: center;
-moz-align-items: center;
-ms-align-items: center;
-o-align-items: center;
-webkit-align-items: center;
align-items: center;
}
/*左右居中*/
.center_left_right{
position: absolute;
left: 50%;
-webkit-transform: translate(-50%, 0);
transform: translate(-50%, 0);
-moz-transform: translate(-50%, 0);
-ms-transform: translate(-50%, 0);
-o-transform: translate(-50%, 0);
}
.ml20 {
margin-left: 20px;
}
</style>
运行结果如下:
顶部栏,右侧三个按钮,从左到右点击功能:最小化、全屏/非全屏(指设置的屏幕最小,即background.js中设置的minWidth、minHeight)、关闭软件
要实现此功能,需要和electron进行用到进程通信:ipcRenderer
// App.vue
import { ipcRenderer } from 'electron'
methods: {
menuClick (type) {
// ipcRenderer向进行发送通知
if (type === 'minmizable') { // 窗口最小化
ipcRenderer.send('minmizable')
} else if (type === 'resizable') { // 窗口最大化/恢复窗口
ipcRenderer.send('maxmizable', this.resizable)
this.resizable = !this.resizable
} else if (type === 'quit') {
ipcRenderer.send('closeApplication')
// if (this.$route.path === '/login') { // 结合实际项目,此处若是登录界面,直接退出软件
// ipcRenderer.send('closeApplication')
// } else { // 如不是登录界面,则在退出前,进行其他操作(比如数据备份、日志记录等功能)
// this.$store.dispatch('app/closeApplication')
// }
}
}
}
// background.js
// 引入ipcMain
import { ipcMain } from 'electron'
//在createWindow函数最底部添加
// 屏幕最小化
ipcMain.on('minmizable', function(event) {
win.minimize()
})
// 设置窗口大小
ipcMain.on('maxmizable', function(event, data) {
if (data) { // 取消窗口最大化.
win.unmaximize()
} else { // 窗口最大化.
win.maximize()
}
})
// 退出软件
ipcMain.on('closeApplication', function(event) {
app.quit()
})
重启项目
点击自定义按钮,实现自定义功能