前言
electron-vue腳手架搭建的項目,在開發階段可能你注意不到項目啟動慢的問題,但是在build 生成的exe可執行文件,啟動后,要反應很久才能進入到app.vue 中加載的頁面,體驗性很差。
正文
針對上訴問題,產生的原因是在渲染進程加載vue的時候,特別慢,為了提高用戶體驗,我們的項目可以在啟動的時候添加一個loading動畫,然后再進入app.vue的頁面。
實現思路
我們可以通過一個單獨的啟動窗口來創建loading頁面,在項目中其他准備工作未完成時出現在用戶的視野中給用戶一定的反饋,等准備工作完成后,通過渲染進程向主進程發送准備完畢的消息,關閉啟動窗口即可。
(1)設置啟動頁面
loading動畫可以寫在一個單獨的html頁面,屬於靜態資源,electron-vue 官網推薦,把靜態資源存放在 /static 目錄下即可,創建loading.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body{ margin: 0; padding: 0; overflow: hidden; background:rgba(0,0,0,.5) } body::-webkit-scrollbar{ display: none; } img{ width: 200px; height: 200px; } </style> </head> <body> <img src="./_.gif" alt="" srcset=""> </body> </html>
(2)修改主進程的index.js ,如下:
import { app, BrowserWindow, ipcMain } from "electron";
import "../renderer/store";
if (process.env.NODE_ENV !== "development") {
global.__static = require("path")
.join(__dirname, "/static")
.replace(/\\/g, "\\\\");
}
let mainWindow, loadingWindow;
const winURL =
process.env.NODE_ENV === "development"
? `http://localhost:9080`
: `file://${__dirname}/index.html`;
const loadingURL =
process.env.NODE_ENV === "development" //加載loading.html頁面地址
? require("path").join(__static, "loading.html")
: `file://${__static}/loading.html`;
const showLoading = (cb) => {
loadingWindow = new BrowserWindow({
show: false,
frame: false, // 無邊框(窗口、工具欄等),只包含網頁內容
width: 200,
height: 200,
resizable: false,
transparent: true, // 窗口是否支持透明,如果想做高級效果最好為true
});
loadingWindow.once("show", cb);
loadingWindow.loadURL(loadingURL);
loadingWindow.show();
};
const createWindow = () => {
mainWindow = new BrowserWindow({
webPreferences: {
nativeWindowOpen: true,
title: "主窗口",
},
height: 563,
width: 1000,
useContentSize: true,
fullscreen: true, // 是否全屏
frame: false, //是否顯示窗口邊框
backgroundColor: "#000000", //設置背景顏色
show: false,
});
mainWindow.loadURL(winURL);
mainWindow.once("ready-to-show", () => {
loadingWindow.hide();
loadingWindow.close();
mainWindow.show();
});
};
app.on("ready", () => {
showLoading(createWindow);
});
上面的代碼中,app在監聽到ready事件時,執行showLoading方法,傳入了createWindow 方法為參數,首先創建loadinWindow窗口,然后注冊show事件,loading窗口加載了loading.html 頁面后,去加載mainWindow窗口,改窗口加載了頁面app.vue(即index.html)內容,並注冊了 " ready-to-show "事件,改事件用於關閉loading窗口,顯示mainWindow窗口。
注意:electron-vue 提供了一個名為 __static 的全局變量,它將產生一個指向 static/ 目錄的正確路徑。
(3)在app.vue中調用 " ready-to-show " 事件
<template> <div id="app"> <router-view></router-view> </div> </template> <script> export default { name: "person-clsoe-system", created() { this.$electron.ipcRenderer.send("ready-to-show"); }, }; </script> <style> /* CSS */ </style>
然后打包測試結果如下:



