【问题标题】:How to init DataTable in Vue3 application after table render表格渲染后如何在 Vue3 应用程序中初始化 DataTable
【发布时间】:2025-12-26 13:50:18
【问题描述】:

我有一个 Vue3 组件,它向服务器发出 ajax 请求,该服务器将带有文章的数组发送回来。然后我需要根据填充模型通过 v-for 渲染 html 表,然后通过 DataTable() 调用这个渲染的表来初始化 DataTable。但似乎问题在于 DataTable() 调用在 html 表呈现之前运行,因此表为空。

ajax 代码如下:

getArticles() 
{
    axios.get( apiRoutes.ARTICLES_URL )            
        .then((response) => {
            let data = response.data.articles;

            // Fill the model
            this.articles = data;

            // Init DataTable
            $('#dataTable').DataTable({ ... });

            //setTimeout(this.setDataTable, 3000);  // This works but want to avoid it.
        })
},

模板代码

<template>
    <div class="table-responsive">
        <table :id="id" class="table table-bordered nowrap" width="100%;">
            <thead>
                <tr>
                    <th>id</th>
                    <th>Title</th>
                    <th>Created</th>
                    <th>Visible</th>
                    <th>User</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="article in articles" :key="article.id">
                    <td>{{article.id}}</td>
                    <td>{{article.title}}</td>
                    <td data-order='{{article.created_at}}'>{{getCreatedAt(article.created_at)}}</td>
                    <td>{{article.visible}}</td>
                    <td>{{article.user.name}}</td>
                    <td>
                        <a href="#" @click.prevent="toggleVisibility(article.id)">{{article.visible === 1 ? 'hide' : 'show'}}</a>
                        <a href="#" @click.prevent="deleteArticle(article.id)" class="text-danger">delete</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

问题是如何正确等待渲染完成?感谢您的帮助。

【问题讨论】:

    标签: vue.js datatables render vuejs3


    【解决方案1】:

    所以如果我理解它,我需要使用$nextTick(),它会在 DOM 渲染完成时等待。

    【讨论】: