electron+vue3實(shí)現(xiàn)自動(dòng)更新的示例代碼
1. 下載更新插件
npm install electron-log --save npm install electron-updater --save
2.electron主進(jìn)程添加更新
2.1 更新封裝
// electron/ipc/api/updater.js
const { autoUpdater } = require('electron-updater')
const { dialog, BrowserWindow } = require('electron')
const log = require('electron-log')
// 配置日志
autoUpdater.logger = log
autoUpdater.logger.transports.file.level = 'info'
// 自動(dòng)更新狀態(tài)
let updateState = {
isChecking: false, // 標(biāo)記是否正在檢查更新
isDownloading: false, // 標(biāo)記是否正在下載更新包
downloadProgress: 0, // 記錄下載進(jìn)度百分比 (0-100)
lastError: null, // 記錄最后一次錯(cuò)誤
updateAvailable: false, // 標(biāo)記是否有可用更新
updateDownloaded: false // 標(biāo)記更新是否已下載完成
}
// 主窗口引用
let mainWindow = null
/**
* 設(shè)置主窗口引用
*/
function setMainWindow(window) {
mainWindow = window
}
/**
* 檢查更新
*/
async function checkForUpdates(event, options = {}) {
if (updateState.isChecking) {
return { success: false, message: '正在檢查更新中...' }
}
try {
updateState.isChecking = true
updateState.lastError = null
console.log('開始檢查更新...')
// 發(fā)送檢查開始消息
if (mainWindow) {
mainWindow.webContents.send('updater:updateMessage', '正在檢查更新...')
}
const result = await autoUpdater.checkForUpdates()
// 如果沒有找到更新,autoUpdater 會(huì)觸發(fā) 'update-not-available' 事件
if (result) {
console.log('發(fā)現(xiàn)更新:', result.updateInfo.version)
return {
success: true,
message: `發(fā)現(xiàn)新版本 v${result.updateInfo.version}`,
version: result.updateInfo.version
}
}
return { success: true, message: '正在檢查更新...' }
} catch (error) {
console.error('檢查更新失敗:', error)
updateState.lastError = error.message
// 發(fā)送錯(cuò)誤消息
if (mainWindow) {
mainWindow.webContents.send('updater:updateError', error.message)
}
return {
success: false,
message: `檢查更新失敗: ${error.message}`
}
} finally {
updateState.isChecking = false
}
}
/**
* 退出并安裝更新
*/
async function quitAndInstall(event) {
try {
console.log('準(zhǔn)備退出并安裝更新...')
autoUpdater.quitAndInstall()
return { success: true }
} catch (error) {
console.error('安裝更新失敗:', error)
return {
success: false,
message: `安裝更新失敗: ${error.message}`
}
}
}
/**
* 獲取更新狀態(tài)
*/
async function getUpdateStatus(event) {
return {
...updateState,
currentVersion: require('../../package.json').version
}
}
/**
* 初始化自動(dòng)更新監(jiān)聽器
*/
function initializeAutoUpdater() {
// 檢查更新中
autoUpdater.on('checking-for-update', () => {
console.log('正在檢查更新...')
updateState.isChecking = true
if (mainWindow) {
mainWindow.webContents.send('updater:updateMessage', '正在檢查更新...')
}
})
// 發(fā)現(xiàn)新版本
autoUpdater.on('update-available', (info) => {
console.log('發(fā)現(xiàn)新版本:', info.version)
updateState.updateAvailable = true
updateState.isChecking = false
if (mainWindow) {
mainWindow.webContents.send('updater:updateAvailable', info)
mainWindow.webContents.send('updater:updateMessage', `發(fā)現(xiàn)新版本 v${info.version},正在下載...`)
}
// 可選:顯示更新提示對(duì)話框
if (mainWindow && process.env.NODE_ENV !== 'development') {
dialog.showMessageBox(mainWindow, {
type: 'info',
title: '發(fā)現(xiàn)新版本',
message: `發(fā)現(xiàn)新版本 v${info.version}`,
detail: '新版本正在后臺(tái)下載,下載完成后將提示您安裝。',
buttons: ['確定']
})
}
})
// 沒有新版本
autoUpdater.on('update-not-available', (info) => {
console.log('當(dāng)前已是最新版本')
updateState.isChecking = false
updateState.updateAvailable = false
if (mainWindow) {
mainWindow.webContents.send('updater:updateNotAvailable', info)
mainWindow.webContents.send('updater:updateMessage', '當(dāng)前已是最新版本')
}
})
// 下載進(jìn)度
autoUpdater.on('download-progress', (progressObj) => {
updateState.isDownloading = true
updateState.downloadProgress = Math.floor(progressObj.percent)
const progressMessage = `下載進(jìn)度: ${progressObj.percent}% (${progressObj.transferred}/${progressObj.total})`
console.log(progressMessage)
if (mainWindow) {
mainWindow.webContents.send('updater:downloadProgress', progressObj)
mainWindow.webContents.send('updater:updateMessage', progressMessage)
}
})
// 下載完成
autoUpdater.on('update-downloaded', (info) => {
console.log('更新下載完成,準(zhǔn)備安裝')
updateState.isDownloading = false
updateState.updateDownloaded = true
updateState.downloadProgress = 100
if (mainWindow) {
mainWindow.webContents.send('updater:updateDownloaded', info)
mainWindow.webContents.send('updater:updateMessage', '更新下載完成,準(zhǔn)備安裝')
}
// 提示用戶安裝更新
if (mainWindow && process.env.NODE_ENV !== 'development') {
dialog.showMessageBox(mainWindow, {
type: 'info',
title: '更新就緒',
message: `新版本 v${info.version} 已下載完成`,
detail: '應(yīng)用將在關(guān)閉后自動(dòng)安裝更新。',
buttons: ['立即重啟', '稍后重啟']
}).then((result) => {
if (result.response === 0) {
autoUpdater.quitAndInstall()
}
})
}
})
// 更新錯(cuò)誤
autoUpdater.on('error', (err) => {
console.error('更新錯(cuò)誤:', err)
updateState.isChecking = false
updateState.isDownloading = false
updateState.lastError = err.message
if (mainWindow) {
mainWindow.webContents.send('updater:updateError', err.message)
mainWindow.webContents.send('updater:updateMessage', `更新錯(cuò)誤: ${err.message}`)
}
})
console.log('自動(dòng)更新監(jiān)聽器初始化完成')
}
module.exports = {
checkForUpdates,
quitAndInstall,
getUpdateStatus,
initializeAutoUpdater,
setMainWindow
}
2.2 主進(jìn)程添加更新檢查
const { initializeAutoUpdater, setMainWindow } = require(path.resolve(__dirname, '../ipc/api/updater'))
function createWindow() {
......
// 1 設(shè)置主窗口引用給更新模塊
setMainWindow(mainWindow)
// 2 初始化自動(dòng)更新(僅生產(chǎn)環(huán)境)
if (!config.isDev) {
initializeAutoUpdater()
// 應(yīng)用加載完成后自動(dòng)檢查更新
mainWindow.webContents.once('did-finish-load', () => {
setTimeout(() => {
console.log('應(yīng)用加載完成,開始自動(dòng)檢查更新...')
// 通過 IPC 調(diào)用檢查更新
mainWindow.webContents.send('updater:autoCheck')
}, 3000)
})
}
// 監(jiān)聽窗口關(guān)閉后事件
mainWindow.on('closed', () => {
console.log('mainWindow closed', " 主進(jìn)程關(guān)閉 窗口已關(guān)閉...")
mainWindow = null
// 3刪除主窗口引用
setMainWindow(null)
})
}
2.3 維護(hù)preload.js
3 渲染進(jìn)程封裝組件
// electron更新組件
import AppUpdater from '@/components/AppUpdater'
APP.VUE中引用組件
<template>
<!-- element-plus 國(guó)際化組件處理 -->
<el-config-provider :locale="elementLocales[effectiveLang]">
<router-view />
<AppUpdater />
</el-config-provider>
</template>
4 配置 package.json
"build": {
......
"publish": [
{
"provider": "github",
"owner": "github用戶名",
"repo": "github項(xiàng)目名"
}
],
......
5 github上維護(hù)最新版本
5.1 創(chuàng)建倉(cāng)庫(kù)
5.2 創(chuàng)建release
項(xiàng)目右側(cè)-> 點(diǎn)擊release -> New 或者 Draft a new release -> new Tag -> 寫 release title -> 上傳文件:
1 可執(zhí)行的安裝文件;
2 latest0tml 文件;
-> 最后 Publish release
6 測(cè)試更新
打包一個(gè)低版本-> 安裝使用 -> 開始就會(huì)檢查版本,如果有新的版本提示是否安裝 -> 是 退出安裝,否 稍后安裝!
注意:設(shè)置了環(huán)境只有生產(chǎn)環(huán)境才會(huì)檢查!
到此這篇關(guān)于electron+vue3實(shí)現(xiàn)自動(dòng)更新的示例代碼的文章就介紹到這了,更多相關(guān)electron vue3自動(dòng)更新內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決Vue.js父組件$on無法監(jiān)聽子組件$emit觸發(fā)事件的問題
今天小編就為大家分享一篇解決Vue.js父組件$on無法監(jiān)聽子組件$emit觸發(fā)事件的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-09-09
vue.js watch經(jīng)常失效的場(chǎng)景與解決方案
這篇文章主要給大家介紹了關(guān)于vue.js watch經(jīng)常失效的場(chǎng)景與解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Vue之Element級(jí)聯(lián)選擇器多選傳值以及回顯方式(樹形結(jié)構(gòu))
這篇文章主要介紹了Vue之Element級(jí)聯(lián)選擇器多選傳值以及回顯方式(樹形結(jié)構(gòu)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
關(guān)于vue3使用particles粒子特效的問題
這篇文章主要介紹了關(guān)于vue3使用particles粒子特效的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06

