1、項目搭建javascript
electron-vue是vue-cli和electron結合的項目,比單獨使用vue構建起的electron項目要方便不少.vue
1.初始化項目並運行java
vue init simulatedgreg/electron-vue my-project cd my-project npm install npm run dev
文件結構web
2.主進程main/index的配置 寬、高、菜單欄、窗口最大化,詳細配置請查看electron官方文檔 https://electronjs.org/docs/api/browser-windowvue-cli
3.package.json的配置npm
4.其它框架按需引入便可.json
2、主進程和渲染器進程之間的通訊api
主進程向渲染器之間的進程通訊使用ipcMain.on(監聽)和ipcMain.send(發送)兩個方法,渲染器進程向主進程使用ipcRenderer.on和ipcRenderer.send()詳情參考:https://electronjs.org/docs/api/ipc-main服務器
3、軟件自動更新架構
1.在package.json中增長publish,並下載electron-updater(版本太高可能會有影響)
"publish": [ { "provider": "generic", "url": "http://127.0.0.1:8080" //存放更新包的地址 } ],
注意在開發環境測試時,項目版本及更新版本號都能能低於electron-updater和electron的版本。打包安裝後更新則是正常的。
2.在主進程main/index中
const { autoUpdater } = require('electron-updater'); const uploadUrl = `http://127.0.0.1:8080`; // 更新包位置 function updateHandle() { let message = { error: '檢查更新出錯', checking: '正在檢查更新……', updateAva: '檢測到新版本,正在下載……', updateNotAva: '如今使用的就是最新版本', }; autoUpdater.setFeedURL(uploadUrl); autoUpdater.on('error', function (message) { sendUpdateMessage( message.error) }); autoUpdater.on('checking-for-update', function () { sendUpdateMessage(message.checking) }); autoUpdater.on('update-available', function (info) { sendUpdateMessage(message.updateAva) }); autoUpdater.on('update-not-available', function (info) { sendUpdateMessage(message.updateNotAva); }); // 更新下載進度事件 autoUpdater.on('download-progress', function (progressObj) { mainWindow.webContents.send('downloadProgress', progressObj) }) autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) { ipcMain.on('isUpdateNow', (e, arg) => { console.log(arguments); console.log("開始更新"); //some code here to handle event autoUpdater.quitAndInstall(); }); mainWindow.webContents.send('isUpdateNow') }); ipcMain.on("checkForUpdate",()=>{ //執行自動更新檢查 autoUpdater.checkForUpdates(); }) } // 經過main進程發送事件給renderer進程,提示更新信息 function sendUpdateMessage(text) { mainWindow.webContents.send('message', text) }
在createWindow()方法中調用updateHandle();
在入口vue頁面中增長監聽方法,這段代碼能夠放在created中也能夠根據須要放在methods中。
let _this = this; _this.$electron.ipcRenderer.send("checkForUpdate"); _this.$electron.ipcRenderer.on("message", (event, text) { _this.tips = text; console.log(text); alert(text); }); _this.$electron.ipcRenderer.on("downloadProgress", (event, progressObj)=> { _this.downloadPercent = progressObj.percent || 0; }); _this.$electron.ipcRenderer.on("isUpdateNow", () => { _this.$electron.ipcRenderer.send("isUpdateNow"); });
三、服務器文件中包含.exe文件和latest.yml文件
4、結語
對與和底層交互性不強的b/s架構項目,elecrton-vue確實方便不少,至關於在vue的基礎上又作了增強。何況electron-vue也支持打包成web端,打包文件在dist/web文件夾下。遇到的坑是在更新上,目前win開發環境下版本號必須都要大於electron-updater和electron的版本號,其它的仍是比較愉快。