This commit is contained in:
2025-09-26 16:27:27 +08:00
parent 1d0bab7804
commit fcc5755dad
11 changed files with 403 additions and 745 deletions

View File

@@ -1,6 +1,7 @@
{
"appId": "com.erp.client",
"productName": "ERP客户端",
"productName": "erpClient",
"asar": true,
"directories": {
"output": "dist"
},
@@ -12,7 +13,7 @@
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true,
"shortcutName": "ERP客户端"
"shortcutName": "erpClient"
},
"win": {
"target": "nsis",
@@ -40,5 +41,11 @@
"!build",
"!dist",
"!scripts"
],
"extraResources": [
{
"from": "update-helper.bat",
"to": "../update-helper.bat"
}
]
}

View File

@@ -1,16 +1,19 @@
// 主进程:创建窗口、启动后端 JAR、隐藏菜单栏
import {app, BrowserWindow, ipcMain, session, Menu, screen} from 'electron';
import { Socket } from 'net';
import { existsSync } from 'fs';
import {app, BrowserWindow, ipcMain, Menu, screen} from 'electron';
import { existsSync, createWriteStream, promises as fs, statSync } from 'fs';
import {join, dirname} from 'path';
import {spawn, ChildProcessWithoutNullStreams} from 'child_process';
import * as https from 'https';
import * as http from 'http';
// 保存后端进程与窗口引用,便于退出时清理
let springProcess: ChildProcessWithoutNullStreams | null = null;
let mainWindow: BrowserWindow | null = null;
let splashWindow: BrowserWindow | null = null;
let appOpened = false;
let downloadProgress = { percentage: 0, current: '0 MB', total: '0 MB', speed: '' };
let isDownloading = false;
let downloadedFilePath: string | null = null;
function openAppIfNotOpened() {
if (appOpened) return;
appOpened = true;
@@ -18,10 +21,12 @@ function openAppIfNotOpened() {
mainWindow.show();
mainWindow.focus();
}
if (splashWindow) { splashWindow.close(); splashWindow = null; }
if (splashWindow) {
splashWindow.close();
splashWindow = null;
}
}
// 启动后端 Spring Boot使用你提供的绝对路径
function startSpringBoot() {
const jarPath = 'C:/Users/ZiJIe/Desktop/wox/RuoYi-Vue/ruoyi-admin/target/ruoyi-admin.jar';
@@ -30,61 +35,44 @@ function startSpringBoot() {
detached: false
});
// 打印后端日志,监听启动成功标志
springProcess.stdout.on('data', (data) => {
console.log(`SpringBoot: ${data}`);
// 检测到启动成功日志立即进入主界面
if (data.toString().includes('Started RuoYiApplication')) {
openAppIfNotOpened();
}
});
// 打印后端错误,检测启动失败
springProcess.stderr.on('data', (data) => {
console.error(`SpringBoot ERROR: ${data}`);
const errorStr = data.toString();
// 检测到关键错误信息,直接退出
if (errorStr.includes('APPLICATION FAILED TO START') ||
errorStr.includes('Port') && errorStr.includes('already in use') ||
errorStr.includes('Unable to start embedded Tomcat')) {
console.error('后端启动失败,程序即将退出');
app.quit();
}
});
// 后端退出时,前端同步退出
springProcess.on('close', (code) => {
console.log(`SpringBoot exited with code ${code}`);
if (mainWindow) {
mainWindow.close();
} else {
app.quit();
}
mainWindow ? mainWindow.close() : app.quit();
});
}
// 关闭后端进程Windows 使用 taskkill 结束整个进程树)
function stopSpringBoot() {
if (!springProcess) return;
try {
if (process.platform === 'win32') {
// Force kill the whole process tree on Windows
try {
const pid = springProcess.pid;
if (pid !== undefined && pid !== null) {
spawn('taskkill', ['/pid', String(pid), '/f', '/t']);
} else {
springProcess.kill();
}
} catch (e) {
// Fallback
const pid = springProcess.pid;
if (pid) {
spawn('taskkill', ['/pid', String(pid), '/f', '/t']);
} else {
springProcess.kill();
}
} else {
springProcess.kill('SIGTERM');
}
} catch (e) {
console.error('Failed to stop Spring Boot process:', e);
console.error('Failed to stop Spring Boot:', e);
} finally {
springProcess = null;
}
@@ -96,7 +84,7 @@ function createWindow () {
height: 800,
show: false,
autoHideMenuBar: true,
icon: join(__dirname, '../renderer/icon/icon.png'), // 添加窗口图标
icon: join(__dirname, '../renderer/icon/icon.png'),
webPreferences: {
preload: join(__dirname, 'preload.js'),
nodeIntegration: false,
@@ -104,16 +92,14 @@ function createWindow () {
}
});
// 彻底隐藏原生菜单栏
try {
Menu.setApplicationMenu(null);
mainWindow.setMenuBarVisibility(false);
if (typeof (mainWindow as any).setMenu === 'function') {
(mainWindow as any).setMenu(null);
}
} catch {}
mainWindow.webContents.openDevTools();
Menu.setApplicationMenu(null);
mainWindow.setMenuBarVisibility(false);
mainWindow.webContents.once('did-finish-load', () => {
setTimeout(() => checkPendingUpdate(), 500);
});
// 生产环境加载本地文件
if (process.env.NODE_ENV === 'development') {
const rendererPort = process.argv[2] || 8083;
mainWindow.loadURL(`http://localhost:${rendererPort}`);
@@ -123,16 +109,12 @@ function createWindow () {
}
app.whenReady().then(() => {
// 预创建主窗口(隐藏)
createWindow();
// 显示启动页
const { width: sw, height: sh } = screen.getPrimaryDisplay().workAreaSize;
const splashW = Math.min(Math.floor(sw * 0.8), 1800);
const splashH = Math.min(Math.floor(sh * 0.8), 1200);
splashWindow = new BrowserWindow({
width: splashW,
height: splashH,
width: Math.min(Math.floor(sw * 0.8), 1800),
height: Math.min(Math.floor(sh * 0.8), 1200),
frame: false,
transparent: false,
resizable: false,
@@ -141,37 +123,23 @@ app.whenReady().then(() => {
center: true,
});
const candidateSplashPaths = [
join(__dirname, '../../public', 'splash.html'),
];
const foundSplash = candidateSplashPaths.find(p => existsSync(p));
if (foundSplash) {
splashWindow.loadFile(foundSplash);
const splashPath = join(__dirname, '../../public', 'splash.html');
if (existsSync(splashPath)) {
splashWindow.loadFile(splashPath);
}
// 注释掉后端启动,便于快速调试前端
// startSpringBoot();
setTimeout(() => openAppIfNotOpened(), 1000);
// 快速调试模式 - 直接打开主窗口
setTimeout(() => {
openAppIfNotOpened();
}, 1000);
app.on('activate', function () {
// 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.
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', function () {
app.on('window-all-closed', () => {
stopSpringBoot();
if (process.platform !== 'darwin') app.quit()
if (process.platform !== 'darwin') app.quit();
});
app.on('before-quit', () => {
@@ -180,5 +148,199 @@ app.on('before-quit', () => {
ipcMain.on('message', (event, message) => {
console.log(message);
})
});
function checkPendingUpdate() {
try {
const updateFilePath = join(process.resourcesPath, 'app.asar.update');
const appAsarPath = join(process.resourcesPath, 'app.asar');
if (!existsSync(updateFilePath)) return;
const appDir = dirname(process.execPath);
const helperPath = join(appDir, 'update-helper.bat');
if (!existsSync(helperPath)) {
console.error('[UPDATE] 更新助手不存在:', helperPath);
return;
}
const vbsPath = join(app.getPath('temp'), 'update-silent.vbs');
const vbsContent = `Set WshShell = CreateObject("WScript.Shell")
WshShell.Run Chr(34) & "${helperPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${appAsarPath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${updateFilePath.replace(/\\/g, '\\\\')}" & Chr(34) & " " & Chr(34) & "${process.execPath.replace(/\\/g, '\\\\')}" & Chr(34), 0, False`;
require('fs').writeFileSync(vbsPath, vbsContent);
spawn('wscript.exe', [vbsPath], {
detached: true,
stdio: 'ignore',
shell: false
});
setTimeout(() => app.quit(), 1000);
} catch (error) {
console.error('[UPDATE] 更新失败:', error);
}
}
ipcMain.handle('download-update', async (event, downloadUrl: string) => {
if (isDownloading) return { success: false, error: '正在下载中' };
if (downloadedFilePath === 'completed') return { success: true, filePath: 'already-completed' };
isDownloading = true;
try {
const isRealDev = process.env.NODE_ENV === 'development' && !app.isPackaged;
if (isRealDev) {
for (let i = 0; i <= 100; i += 10) {
setTimeout(() => {
downloadProgress = {
percentage: i,
current: (i * 0.5).toFixed(1) + ' MB',
total: '50.0 MB',
speed: '2.5 MB/s'
};
if (mainWindow) {
mainWindow.webContents.send('download-progress', downloadProgress);
}
}, i * 100);
}
setTimeout(() => {
downloadedFilePath = 'completed';
isDownloading = false;
}, 1100);
return { success: true, filePath: 'dev-mode-simulated', dev: true };
}
const tempPath = join(app.getPath('temp'), 'app.asar.new');
await downloadFile(downloadUrl, tempPath, (progress) => {
downloadProgress = progress;
if (mainWindow) {
mainWindow.webContents.send('download-progress', progress);
}
});
if (!existsSync(tempPath)) {
throw new Error('下载文件不存在');
}
const fileStats = await fs.stat(tempPath);
if (fileStats.size < 1000) {
throw new Error('下载文件过小');
}
const updateFilePath = join(process.resourcesPath, 'app.asar.update');
await fs.copyFile(tempPath, updateFilePath);
await fs.unlink(tempPath);
if (!existsSync(updateFilePath)) {
throw new Error('更新文件保存失败');
}
downloadedFilePath = 'completed';
isDownloading = false;
return { success: true, filePath: updateFilePath };
} catch (error) {
isDownloading = false;
downloadedFilePath = null;
const tempPath = join(app.getPath('temp'), 'app.asar.new');
if (existsSync(tempPath)) {
fs.unlink(tempPath).catch(() => {});
}
return { success: false, error: error instanceof Error ? error.message : '下载失败' };
}
});
ipcMain.handle('get-download-progress', () => {
return { ...downloadProgress, isDownloading };
});
ipcMain.handle('install-update', async () => {
try {
const isRealDev = process.env.NODE_ENV === 'development' && !app.isPackaged;
if (isRealDev) {
downloadedFilePath = null;
return { success: true, message: '开发环境模拟重启' };
}
const updateFilePath = join(process.resourcesPath, 'app.asar.update');
const hasUpdateFile = existsSync(updateFilePath);
if (!downloadedFilePath || (downloadedFilePath !== 'completed' && !hasUpdateFile)) {
return { success: false, error: '更新文件不存在' };
}
setTimeout(() => {
downloadedFilePath = null;
app.quit();
}, 500);
return { success: true };
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : '重启失败' };
}
});
ipcMain.handle('cancel-download', () => {
isDownloading = false;
downloadProgress = { percentage: 0, current: '0 MB', total: '0 MB', speed: '' };
downloadedFilePath = null;
return { success: true };
});
ipcMain.handle('get-update-status', () => {
const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged || process.defaultApp;
return { downloadedFilePath, isDownloading, downloadProgress, isPackaged: app.isPackaged, isDev };
});
async function downloadFile(url: string, filePath: string, onProgress: (progress: any) => void): Promise<void> {
return new Promise((resolve, reject) => {
const protocol = url.startsWith('https') ? https : http;
protocol.get(url, (response) => {
if (response.statusCode !== 200) {
reject(new Error(`HTTP ${response.statusCode}`));
return;
}
const totalBytes = parseInt(response.headers['content-length'] || '0', 10);
let downloadedBytes = 0;
const startTime = Date.now();
const fileStream = createWriteStream(filePath);
response.on('data', (chunk) => {
downloadedBytes += chunk.length;
const percentage = totalBytes > 0 ? Math.round((downloadedBytes / totalBytes) * 100) : 0;
const current = `${(downloadedBytes / 1024 / 1024).toFixed(1)} MB`;
const total = `${(totalBytes / 1024 / 1024).toFixed(1)} MB`;
const elapsed = (Date.now() - startTime) / 1000;
const speed = elapsed > 0 ? `${((downloadedBytes / elapsed) / 1024 / 1024).toFixed(1)} MB/s` : '';
onProgress({ percentage, current, total, speed });
});
response.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
resolve();
});
fileStream.on('error', (error) => {
fs.unlink(filePath).catch(() => {});
reject(error);
});
}).on('error', reject);
});
}

View File

@@ -0,0 +1,22 @@
import { contextBridge, ipcRenderer } from 'electron'
const electronAPI = {
sendMessage: (message: string) => ipcRenderer.send('message', message),
downloadUpdate: (downloadUrl: string) => ipcRenderer.invoke('download-update', downloadUrl),
getDownloadProgress: () => ipcRenderer.invoke('get-download-progress'),
installUpdate: () => ipcRenderer.invoke('install-update'),
cancelDownload: () => ipcRenderer.invoke('cancel-download'),
getUpdateStatus: () => ipcRenderer.invoke('get-update-status'),
onDownloadProgress: (callback: (progress: any) => void) => {
ipcRenderer.on('download-progress', (event, progress) => callback(progress))
},
removeDownloadProgressListener: () => {
ipcRenderer.removeAllListeners('download-progress')
}
}
contextBridge.exposeInMainWorld('electronAPI', electronAPI)
export type ElectronApi = typeof electronAPI

View File

@@ -416,25 +416,14 @@ async function confirmRemoveDevice(row: DeviceItem & { isCurrent?: boolean }) {
}
}
// 启动时检查更新
async function checkForUpdates() {
// 延迟3秒后自动检查更新
setTimeout(() => {
showUpdateDialog.value = true
}, 3000)
}
onMounted(async () => {
showContent()
await checkAuth()
})
// 启动时检查更新
await checkForUpdates()
// 监听页面关闭断开SSE连接会自动设置离线
window.addEventListener('beforeunload', () => {
SSEManager.disconnect()
})
onUnmounted(() => {
SSEManager.disconnect()
})
</script>
@@ -445,7 +434,6 @@ onMounted(async () => {
<div class="loading-container" id="loading">
<div class="loading-spinner"></div>
</div>
<div class="erp-container">
<div class="sidebar">
<div class="user-avatar">

View File

@@ -2,19 +2,15 @@
<div>
<div class="version-info" @click="autoCheck">v{{ version || '-' }}</div>
<el-dialog v-model="show" width="522px" :close-on-click-modal="false" align-center class="update-dialog" title="软件更新"
:show-close="true"
custom-class="update-dialog">
<!-- 状态检查更新 -->
<el-dialog v-model="show" width="522px" :close-on-click-modal="false" align-center class="update-dialog" title="软件更新">
<div v-if="stage === 'check'" class="update-content">
<div class="update-layout">
<div class="left-pane">
<img src="/icon/icon.png" class="app-icon app-icon-large" alt="App Icon" />
</div>
<div class="right-pane">
<p class="announce">新版本的"{{ appName || 'App Name' }}"已经发布</p>
<p class="desc">{{ (appName || 'App Name') }} {{ info.latestVersion || '-' }} 可供下载您现在的版本是 {{ version || '-' }}要现在下载吗?</p>
<p class="announce">新版本的"{{ appName }}"已经发布</p>
<p class="desc">{{ appName }} {{ info.latestVersion }} 可供安装您现在的版本是 {{ version }}要现在安装吗</p>
<div class="update-details form">
<h4>更新信息</h4>
@@ -24,21 +20,17 @@
class="notes-box"
:rows="6"
readonly
resize="none"
placeholder="• 优化了用户界面体验&#10;• 修复了已知问题&#10;• 提升了系统稳定性&#10;• 增加了新的功能模块&#10;• 优化了数据处理性能" />
resize="none" />
</div>
<div class="update-actions row">
<div class="auto-update-section">
<el-checkbox v-model="autoUpdateSelected">以后自动下载并安装更新</el-checkbox>
</div>
<div class="update-buttons">
<div class="left-actions">
<el-button size="small" @click="show=false">跳过这个版本</el-button>
</div>
<div class="right-actions">
<el-button size="small" @click="show=false">稍后提醒</el-button>
<el-button size="small" type="primary" @click="start">安装更新</el-button>
<el-button size="small" type="primary" @click="start">下载更新</el-button>
</div>
</div>
</div>
@@ -46,12 +38,11 @@
</div>
</div>
<!-- 状态正在下载 -->
<div v-else-if="stage === 'downloading'" class="update-content">
<div class="update-header text-center">
<img src="/icon/icon.png" class="app-icon" alt="App Icon" />
<h3>正在更新 {{ appName || 'erp' }}</h3>
<p>正在下载新版...</p>
<h3>正在更新 {{ appName }}</h3>
<p>正在下载更新文件...</p>
</div>
<div class="download-progress">
@@ -68,19 +59,22 @@
<span v-if="prog.speed">{{ prog.speed }}</span>
</div>
</div>
<div class="update-buttons">
<el-button @click="cancelDownload">取消下载</el-button>
</div>
</div>
<!-- 状态下载完成 -->
<div v-else-if="stage === 'completed'" class="update-content">
<div class="update-header text-center">
<img src="/icon/icon.png" class="app-icon" alt="App Icon" />
<h3>正在更新 {{ appName || '我了个电商' }}</h3>
<p>可以开始安装了</p>
<h3>更新完成</h3>
<p>更新文件已下载将在重启后自动应用</p>
</div>
<div class="download-progress">
<div class="progress-info">
<span>{{ prog.current }} /{{ prog.total }}</span>
<span>{{ prog.current }} / {{ prog.total }}</span>
</div>
<el-progress
:percentage="100"
@@ -91,7 +85,7 @@
<div class="update-buttons">
<el-button @click="cancelDownload">稍后更新</el-button>
<el-button type="primary" @click="installUpdate">安装并重新启动</el-button>
<el-button type="primary" @click="installUpdate">重启应用新版本</el-button>
</div>
</div>
</el-dialog>
@@ -99,16 +93,12 @@
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateApi } from '../../api/update'
const props = defineProps<{
modelValue: boolean
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
}>()
const props = defineProps<{ modelValue: boolean }>()
const emit = defineEmits<{ 'update:modelValue': [value: boolean] }>()
const show = computed({
get: () => props.modelValue,
@@ -118,154 +108,142 @@ const show = computed({
type Stage = 'check' | 'downloading' | 'completed'
const stage = ref<Stage>('check')
const appName = ref('ERP客户端')
const autoUpdateSelected = ref(false)
const prog = ref({ percentage: 0, current: '0 MB', total: '0 MB', speed: '' })
const version = ref('2.0.0') // 当前版本号
const downloadedFilePath = ref('') // 下载文件路径
const version = ref('2.0.0')
const prog = ref({ percentage: 0, current: '0 MB', total: '0 MB', speed: '' as string | undefined })
const info = ref({
latestVersion: '2.4.8',
downloadUrl: 'https://qiniu.pxdj.tashowz.com/2025/09/f492725041ba43fb8ded9344ec08d646.exe',
downloadUrl: '',
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 增加了新的功能模块\n• 优化了数据处理性能'
})
// 自动检查更新
async function autoCheck() {
try {
ElMessage.info('正在检查更新...')
console.log('手动检查更新...')
ElMessage({ message: '正在检查更新...', type: 'info' })
if (window.electronAPI?.checkForUpdates) {
await window.electronAPI.checkForUpdates()
} else {
// 如果没有 API直接显示更新对话框
setTimeout(() => {
show.value = true
stage.value = 'check'
}, 500)
try {
version.value = await updateApi.getVersion()
} catch (error) {
console.error('获取版本失败:', error)
version.value = '2.0.0'
}
info.value = {
currentVersion: version.value,
latestVersion: '2.4.9',
downloadUrl: 'https://qiniu.pxdj.tashowz.com/2025/09/becac13811214c909d11162d2ff2c863.asar',
updateNotes: '• 优化了用户界面体验\n• 修复了已知问题\n• 提升了系统稳定性\n• 轻量级更新仅替换app.asar',
hasUpdate: true
}
show.value = true
stage.value = 'check'
ElMessage({ message: '发现新版本', type: 'success' })
} catch (error) {
console.error('检查更新失败:', error)
ElMessage.error('检查更新失败')
ElMessage({ message: '检查更新失败', type: 'error' })
}
}
// 开始安装更新
async function start() {
if (!info.value.downloadUrl) {
ElMessage({ message: '下载链接不可用', type: 'error' })
return
}
if (!window.electronAPI) {
ElMessage({ message: '更新功能不可用', type: 'error' })
return
}
stage.value = 'downloading'
prog.value = { percentage: 0, current: '0 MB', total: '0 MB', speed: '' }
try {
if (info.value.downloadUrl && window.electronAPI?.downloadUpdate) {
console.log('开始下载:', info.value.downloadUrl)
window.electronAPI.onDownloadProgress((progress) => {
prog.value = {
percentage: progress.percentage || 0,
current: progress.current || '0 MB',
total: progress.total || '0 MB',
speed: progress.speed || ''
}
})
// 直接打开浏览器下载,不模拟进度
const result = await window.electronAPI.downloadUpdate(info.value.downloadUrl)
if (result.success) {
ElMessage.success('下载链接已在浏览器中打开,请等待下载完成后手动安装')
show.value = false
} else {
throw new Error(result.error)
}
try {
const response = await window.electronAPI.downloadUpdate(info.value.downloadUrl)
if (response.success) {
stage.value = 'completed'
prog.value.percentage = 100
ElMessage({ message: '下载完成', type: 'success' })
} else {
ElMessage.error('下载链接不可用')
show.value = false
ElMessage({ message: '下载失败: ' + (response.error || '未知错误'), type: 'error' })
stage.value = 'check'
}
} catch (error) {
console.error('下载失败:', error)
ElMessage.error('下载失败: ' + error)
show.value = false
}
}
// 取消下载
function cancelDownload() {
show.value = false
stage.value = 'check'
}
// 安装更新
async function installUpdate() {
try {
ElMessage.success('正在安装更新,程序将自动重启...')
console.log('准备安装更新')
// 通过 IPC 重启应用
if (window.electronAPI?.restartApp) {
setTimeout(async () => {
await window.electronAPI.restartApp()
}, 1000) // 延迟1秒重启
} else {
// 如果没有重启API手动关闭窗口
setTimeout(() => {
window.close()
}, 1000)
}
show.value = false
} catch (error) {
console.error('重启失败:', error)
ElMessage.error('重启失败,请手动重启应用')
}
}
// 监听对话框显示
watch(show, async (visible) => {
if (visible) {
await fetchUpdateInfo()
ElMessage({ message: '下载失败', type: 'error' })
stage.value = 'check'
}
})
}
async function fetchUpdateInfo() {
async function cancelDownload() {
try {
// 获取当前版本
if (window.electronAPI?.getVersion) {
const currentVersion = await window.electronAPI.getVersion()
version.value = currentVersion
if (window.electronAPI) {
window.electronAPI.removeDownloadProgressListener()
await window.electronAPI.cancelDownload()
}
show.value = false
stage.value = 'check'
} catch (error) {
console.error('获取更新信息失败:', error)
console.error('取消下载失败:', error)
show.value = false
stage.value = 'check'
}
}
// 监听主进程的更新通知
onMounted(() => {
if (window.electronAPI?.onShowUpdateDialog) {
window.electronAPI.onShowUpdateDialog((updateData) => {
console.log('收到更新通知:', updateData)
async function installUpdate() {
try {
await ElMessageBox.confirm(
'安装过程中程序将自动重启,请确保已保存所有工作。确定要立即安装更新吗?',
'确认安装',
{
confirmButtonText: '立即安装',
cancelButtonText: '取消',
type: 'warning'
}
)
// 更新信息
if (updateData.currentVersion) {
version.value = updateData.currentVersion
}
if (updateData.latestVersion) {
info.value.latestVersion = updateData.latestVersion
}
if (updateData.downloadUrl) {
info.value.downloadUrl = updateData.downloadUrl
}
if (updateData.updateNotes) {
info.value.updateNotes = updateData.updateNotes
}
if (!window.electronAPI) {
ElMessage({ message: '更新功能不可用', type: 'error' })
return
}
// 显示对话框
show.value = true
const response = await window.electronAPI.installUpdate()
if (response.success) {
ElMessage({ message: '应用即将重启', type: 'success' })
setTimeout(() => show.value = false, 1000)
} else {
ElMessage({ message: '重启失败: ' + (response.error || '未知错误'), type: 'error' })
stage.value = 'check'
})
}
} catch (error) {
if (error !== 'cancel') {
console.error('安装失败:', error)
ElMessage({ message: '安装失败', type: 'error' })
}
}
}
// 初始化获取版本信息
fetchUpdateInfo()
onMounted(async () => {
try {
version.value = await updateApi.getVersion()
} catch (error) {
console.error('获取版本失败:', error)
}
})
// 暴露方法供父组件调用
defineExpose({
showUpdate: (updateData: any) => {
if (updateData.currentVersion) version.value = updateData.currentVersion
if (updateData.latestVersion) info.value.latestVersion = updateData.latestVersion
if (updateData.updateNotes) info.value.updateNotes = updateData.updateNotes
if (updateData.downloadUrl) info.value.downloadUrl = updateData.downloadUrl
show.value = true
onUnmounted(() => {
if (window.electronAPI) {
window.electronAPI.removeDownloadProgressListener()
}
})
</script>
@@ -285,7 +263,6 @@ defineExpose({
user-select: none;
}
/* 更新对话框整体样式 */
:deep(.update-dialog .el-dialog) {
border-radius: 16px;
box-shadow: 0 24px 48px rgba(0, 0, 0, 0.15);
@@ -296,29 +273,6 @@ defineExpose({
text-align: left;
}
:deep(.update-dialog .el-dialog__headerbtn) {
top: 12px;
right: 20px;
width: 32px;
height: 32px;
font-size: 18px;
border-radius: 50%;
background-color: transparent;
}
:deep(.update-dialog .el-dialog__headerbtn:hover) {
background-color: #f5f5f5;
}
:deep(.update-dialog .el-dialog__close) {
color: #909399;
font-weight: 400;
}
:deep(.update-dialog .el-dialog__close:hover) {
color: #409EFF;
}
:deep(.update-dialog .el-dialog__body) {
padding: 0;
}
@@ -365,11 +319,6 @@ defineExpose({
margin-bottom: 16px;
}
.update-header-content {
flex: 1;
min-width: 0;
}
.update-header h3 {
font-size: 20px;
font-weight: 600;
@@ -400,28 +349,6 @@ defineExpose({
margin: 0 0 8px 0;
}
.update-details p {
font-size: 13px;
color: #6b7280;
line-height: 1.6;
margin: 0 0 16px 0;
white-space: pre-wrap;
}
.update-details p:last-child {
margin-bottom: 0;
}
.auto-update-section {
margin: 0;
}
:deep(.auto-update-section .el-checkbox) {
color: #374151;
font-size: 14px;
}
.update-actions.row {
display: flex;
flex-direction: column;
@@ -435,16 +362,10 @@ defineExpose({
gap: 12px;
}
/* 检查更新页:按钮单独一行并靠右,不拉伸 */
.update-actions.row .update-buttons { justify-content: space-between; }
:deep(.update-actions.row .update-buttons .el-button) { flex: none; min-width: 100px; }
.left-actions { display: flex; gap: 12px; }
.right-actions { display: flex; }
.update-buttons.text-center {
justify-content: center;
}
.right-actions { display: flex; gap: 8px; }
:deep(.update-buttons .el-button) {
flex: 1;
@@ -453,12 +374,6 @@ defineExpose({
border-radius: 8px;
}
:deep(.update-buttons.text-center .el-button) {
flex: none;
min-width: 140px;
}
/* 下载进度区域 */
.download-progress {
margin: 24px 0;
}
@@ -480,7 +395,6 @@ defineExpose({
justify-content: space-between;
}
/* 进度条自定义样式 */
:deep(.el-progress-bar__outer) {
border-radius: 4px;
background-color: #e5e7eb;
@@ -491,7 +405,6 @@ defineExpose({
transition: width 0.3s ease;
}
/* 按钮样式调整 */
:deep(.update-buttons .el-button--primary) {
background-color: #2563eb;
border-color: #2563eb;
@@ -514,19 +427,4 @@ defineExpose({
background-color: #e5e7eb;
border-color: #9ca3af;
}
/* 响应式调整 */
@media (max-width: 480px) {
.update-content {
padding: 24px 16px;
}
.update-buttons {
flex-direction: column;
}
:deep(.update-buttons .el-button) {
flex: none;
}
}
</style>

View File

@@ -3,6 +3,15 @@
*/
export default interface ElectronApi {
sendMessage: (message: string) => void
downloadUpdate: (downloadUrl: string) => Promise<{ success: boolean; filePath?: string; error?: string }>
getDownloadProgress: () => Promise<{ percentage: number; current: string; total: string; speed: string; isDownloading: boolean }>
installUpdate: () => Promise<{ success: boolean; error?: string }>
cancelDownload: () => Promise<{ success: boolean }>
onDownloadProgress: (callback: (progress: any) => void) => void
removeDownloadProgressListener: () => void
getUpdateStatus: () => Promise<{ downloadedFilePath: string | null; isDownloading: boolean; downloadProgress: any; isPackaged: boolean }>
onUpdateLog: (callback: (log: string) => void) => void
removeUpdateLogListener: () => void
}
declare global {