Implementing Vue.js + DataTables properly
To get the DataTables plugin integrated correctly with Vue, there are a few things to keep in mind:
Per your example, you can use
var dT = $('#app-datatable').DataTable();
to initialize the DataTables if you already have the data ready and rendered to the DOM. If you don't have the DOM<table></table>
fully rendered (perhaps due to data populated via a delayed ajax call), you can't initialize the DataTables until the data is ready. As an example, if you have afetchData
method in your component, you can initialize the DataTable once the promise has been fulfilled.To update the table once initialized, perhaps due to a change in the underlying table data, the best (perhaps the only way), is to first destroy the table, before the new data is received and written to the DOM by Vue:
var dT = $('#app-datatable').DataTable(); dT.destroy();
Then, once the data (in your case, the users array) has been updated, re-initialize the DataTable as so:
this.$nextTick(function() { $('#app-datatable').DataTable({ // DataTable options here... }); })
The $nextTick is necessary to ensure Vue has flushed the new data to the DOM, before re-initializing. If the DOM is updated after the DataTable plugin has been initialized, you'll see the table data, but the usual sorting, paging, etc. won't work.
Another important point, is to have a row id in your dataset, and set the key in the
<tr></tr>
:<tr v-repeat="user: users" track-by="id">
Without the
track-by
, Vue will complain when flushing new data to the DOM after DataTables has been initializing, likely due to not finding DOM elements hi-jacked by DataTables.