代码之家  ›  专栏  ›  技术社区  ›  Jeremy

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

  •  0
  • Jeremy  · 技术社区  · 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>
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Ginger    1 年前

    您可以使用 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);
    
    

    查看所有可用的挂钩 here