Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to execute a function that runs after all the DOM is loaded in nuxtjs?

I created a function that adjusts the size of columns in a table.

When I navigate between pages, it doesn’t launch.

If I refresh the page, thanks to SSR, they execute correctly (because the dom is entirely constructed before the javascript is executed).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is not the case for navigation between pages.

<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>

>Solution :

You may use 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);

see all the available hooks here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading