首页 > 解决方案 > DOM 渲染成 svelte 后执行函数

问题描述

我需要运行在 DOM 完全更新后会发出事件的函数。我将 Svelte 与 Electron.js 结合起来。此页面用作 PDF 生成器,它从主进程加载数据,然后自我更新,最后通知主进程所有内容都已加载,主进程截屏此内容(PDF 进程)。所以代码:

PDF进程渲染器:


    onMount(() => {
        // Asks for the data, emits event
        ipc.send('PDFWindowReady');
    });

    ipc.on('PDFLoadContent',(event,data)=>{
        // Gets the data, event listener
        const content = data.data;

        // Assigns the data to a particular variable
        contractorEnterprise = content.contractor.enterprise;
        contractorAddress = content.contractor.street;
        contractorCity = content.contractor.city;

        //long list of assignments

        output = data.output;
        // Renders empty PDF, that means, that DOM has not re-rendered yet
        // I need to ensure that it has, then execute function below
        //ipc.send('makePDF',data.output)
    });

    beforeUpdate(async () => {
        // This doesn't work, empty PDF
        await tick();
        if (output) {
            await tick();
            ipc.send('makePDF',output);
            console.log(output);
        }
    });

    /*
    afterUpdate(() => {
        // This neither
        if (output) {
            ipc.send('makePDF',output)
        }
    });
    */

    ipc.on('PDFCreated',()=>{
        // after PDF is generated, window will be closed
        /* I even tried timeouts, but that is unreliable and could cause unloaded content
           on big data load */
        //setTimeout(() => {
        window.close()
        //},1000);
    });

电子.js(main.js):

ipcMain.on('makePDF', (event,aux)=>{
    const pdfPath = path.join(appRoot.pdfPath,aux.file);
    const content = BrowserWindow.fromWebContents(event.sender);
    content.webContents.printToPDF({
        pageSize: "A4",
        landscape: false
    }).then(data => {
        fs.writeFile(pdfPath, data, (error) => {
            event.sender.send('PDFCreated');
            if (error) throw error;
            new Notification({
                title: 'PDF je hotové',
                body: `Exportovanie dodacieho listu do ${pdfPath}.pdf bolo ukončené.`
            }).show();
            shell.openExternal(`file://${pdfPath}`);
            console.log(`New delivery note:${pdfPath}`);
        })
    }).catch(error => {
        console.log(error.message)
    })
});

//triggered by primary process
ipcMain.on('openPDFWindow',(event,data)=>{
    //opens new invisible browser window
    fpt.createPDFWindow();
    ipcMain.once('PDFWindowReady',(event)=>{
        //as soon as is window ready event is emmited
        event.sender.send('PDFLoadContent',data);
    });
});

第 76 行的输出,console.log(output):

包含输出文件名称的对象

如您所见,我在页面加载后发送事件的任何尝试都不起作用。问题是它呈现空的PDF。以前我使用 jQuery 并通过超时解决了它,但这是愚蠢的容易出错的解决方案。我需要在渲染完所有内容后运行此函数:

ipc.send('makePDF',output)

问题是它渲染的是空的 PDF,看起来页面没有重新渲染并且截图太早了。有可靠的解决方案吗?

标签: javascriptelectronsvelte

解决方案


推荐阅读