如何在nuxtjs中执行所有DOM加载完毕后运行的函数?

问题描述 投票:0回答:1

我创建了一个调整表中列大小的函数。

当我在页面之间导航时,它不会启动。

如果我刷新页面,感谢 SSR,它们会正确执行(因为 dom 是在执行 javascript 之前完全构建的)。

页面之间的导航并非如此。

<script setup>
// Function to adjust column widths
const adjustTableColumnWidths = () => {
    const tables = document.querySelectorAll('.prose table');

    tables.forEach((table) => {
        const totalWidth = table.offsetWidth;
        const firstColWidth = totalWidth / 3; // Largeur de la première colonne
        const otherColWidth = (totalWidth - firstColWidth) / (table.rows[0].cells.length - 1); // Width of other columns

        // Go through all table rows to fit columns
        Array.from(table.rows).forEach(row => {
            // Ajuster la première colonne
            const firstCell = row.cells[0];
            if (firstCell) {
                firstCell.style.width = `${firstColWidth}px`;
            }

            // Adjust the other columns
            for (let i = 1; i < row.cells.length; i++) {
                const cell = row.cells[i];
                cell.style.width = `${otherColWidth}px`;
            }
        });
    });
};

// Call the function after the content is loaded and rendered
onMounted(async () => {
    await nextTick(); // Wait for the next 'tick' for the DOM rendering to complete
    adjustTableColumnWidths();
    // Add an event handler for window resizing
    window.addEventListener('resize', adjustTableColumnWidths);
});

// Clean event listener when unmounting component
onUnmounted(() => {
    window.removeEventListener('resize', adjustTableColumnWidths);
});
</script>
javascript nuxt.js nuxtjs3
1个回答
0
投票

您可以使用Lifecycle Hooks


const nuxtApp = useNuxtApp();

// Called on Suspense resolved event.
nuxtApp.hook('page:finish', adjustTableColumnWidths);

// After page transition onAfterLeave event.
nuxtApp.hook('page:transition:finish', adjustTableColumnWidths);

在此处查看所有可用的挂钩。

© www.soinside.com 2019 - 2024. All rights reserved.