Vue3 + DataTables redraw the table after delete

542 Views Asked by At

I have a Vue3 component that renders tables based on model data. Then I add DataTables functionality to the table to be able to filter and sorting data. Everything works fine. But if I click on the delete button I need to send a delete ajax request to the server and then on success redraw the whole table with new data. I tried to use draw() method but it does not work. Deleted rows are still in the table. I don't know if I need to remove the whole table and create it again or there is another solution. This is the Vue template code.

<template>
    <div class="table-responsive">
        <table :id="id" class="table table-bordered nowrap" width="100%;">
            <thead>
                <tr>
                    <th>id</th>
                    <th>Title</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>{{article.visible}}</td>
                    <td>{{article.user.name}}</td>
                    <td>
                        <a href="#" @click.prevent="deleteArticle(article.id)" class="text-danger">delete</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

And this is the deleteArticle() code

deleteArticle(id) {
    axios.get( apiRoutes.ARTICLE_DELETE_URL + id )
        .then( response => {
            this.getArticles();
        })
        .catch( response => {
            console.log(response);
        }); 
},

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

            this.$nextTick(function() {
                this.setDataTable();
            });
        })
        .catch((response) => {
            console.log(response);
        });
},

setDataTable() {
    var table = $('#'+this.id);

    if( this.dataTableObject ) 
    {
        this.dataTableObject.reload().draw();  // This is the code I need to fix
        return;
    }

    ...
},

What is the right flow of this component?

0

There are 0 best solutions below