Fork me on GitHub

三步搞定electron-vue-软件自动更新

image.png

  1. 安装依赖npm i electron-updater,package.json配置buildpublish参数如下:
    image.png

  2. 主进程添加代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    import { autoUpdater } from 'electron-updater'

    // 检测更新,在你想要检查更新的时候执行,renderer事件触发后的操作自行编写
    !function updateHandle() {
    let message = {
    error: '检查更新出错',
    checking: '正在检查更新……',
    updateAva: '检测到新版本,正在下载……',
    updateNotAva: '现在使用的就是最新版本,不用更新',
    };
    const os = require('os');
    const uploadUrl = "http://61.4.184.177:7799/download/"; // 下载地址,不加后面的**.exe
    autoUpdater.setFeedURL(uploadUrl);
    autoUpdater.on('error', function (error) {
    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)
    }
  3. 渲染进程添加代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    created(){
    const _this = this
    _this.$electron.ipcRenderer.send("checkForUpdate");
    _this.$electron.ipcRenderer.on("message", (event, text) => {
    console.log(arguments);
    _this.tips = text;
    alert(text)
    });
    _this.$electron.ipcRenderer.on("downloadProgress", (event, progressObj)=> {
    console.log(progressObj);
    _this.downloadPercent = progressObj.percent || 0;
    });
    _this.$electron.ipcRenderer.on("isUpdateNow", () => {
    _this.$electron.ipcRenderer.send("isUpdateNow");
    });
    },
    beforeDestroy(){
    // this.$electron.ipcRenderer.removeAll(["message", "downloadProgress", "isUpdateNow"]);
    }

打包,将生成的exe文件和latest.yml文件上传至服务器
image.png

引用 electron-vue autoupdater