[Vuejs]-Using jquery Datatables with vue.js

3👍

You should avoid mixing Vue-managed templates and jQuery. They operate under different paradigms and your end code will likely suffer from maintainability issues down the road.

That said, your demo has a few issues:

  • That <template> element inside your HTML has no use, remove it.
  • You should give Vue some time to render the changes on this.users before calling $().DataTable(). You can do that using Vue.nextTick().

See working demo below.

const { createApp } = Vue

const app = createApp({
    data() {
        return {
            users:[]
        }
    },
    mounted() {
        $.ajax({
            url: 'https://jsonplaceholder.typicode.com/todos/',
            method: 'GET',
            dataType: 'json',
            contentType: 'application/json',
            success: res => {   
                this.users = res;

                Vue.nextTick(() => {
                  $('#example').DataTable();
                });
            }
        });
    }
});

app.mount('#arbeitsbereich');
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

<section id="arbeitsbereich">
  <h1>Test</h1>

  <table class="table table-hover table-bordered" id="example">
    <thead>
      <tr>
        <th>User-ID</th>
        <th>ID</th>
        <th>Title</th>
        <th>Completed</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="user in users" :key="user.id">
        <td>{{user.userId}}</td>
        <td>{{user.id}}</td>
        <td>{{user.title}}</td>
        <td>{{user.completed}}</td>
      </tr>
    </tbody>
  </table>
</section>

Leave a comment