Wednesday 22nd June, 2022
By Allan Jardine

Vue3 component

Vue.js is a front-end Javascript framework that is widely used for creating reactive web-applications. It is consistently one of the most popular frameworks around, and in this post I will introduce a the datatables.net-vue3 package that provides DataTables for use as a component in Vue3 applications.

Want to dive right into the code with some examples? This is a coding blog, of course you do! The following examples show DataTables being used in a Vue3 application on Stackblitz which allows us to run an entire Node.js based app. The examples use Vue3's composition API and Vite for the build process.

Installation

First thing to do is install the datatables.net-vue3 application with:

# npm
npm install --save datatables.net-vue3

# yarn
yarn add datatables.net-vue3

The package has dependencies on datatables.net and jquery which are automatically bundled in, so you don't need any other packages if you just want to display an interactive table.

To then use the component in your own components, import it using:

import DataTable from 'datatables.net-vue3';

which will give you a <DataTable> Vue component you can use in your templates.

Extensions

You can also install DataTables extensions from their own npm packages and use them in the standard manner - e.g. for Select you might use:

# npm
npm install --save datatables.net-select

# yarn
yarn add datatables.net-select

Each extension that is added, will need to be registered with the DataTable component which is done using the static DataTable.use() method on the component - e.g.:

import DataTable from 'datatables.net-vue3'
import Select from 'datatables.net-select';

DataTable.use(Select);

The same applies to all of the other DataTables extensions. Use the download builder to get a list of the npm packages for the extensions you want (and also the styling packages - see below).

Use

Once installed and registered in your component you will have a <DataTable> component available - it as a single optional slot which can be used to describe the table with headers and footers:

<DataTable class="display">
    <thead>
        <tr>
            <th>First</th>
            <th>Second</th>
        </tr>
    </thead>
</DataTable>

Important: Do not use a Vue for statement to populate the table with data unless the data is static (i.e. not reactive). Doing so would cause both DataTables and Vue to try and control the same DOM elements, resulting in unpredictable behaviour. Bind data using the data parameter!

The <DataTable> component has the following parameters available:

  • columns - Define the columns array used for DataTables initialisation
  • data - Data array for DataTables. This is optional and if you are using Ajax to load the DataTable data is not required.
  • ajax - Ajax option for DataTables - to load data for the table over Ajax.
  • class - Class name to assign to the table tag
  • options - The DataTables options for the table. Note that this can include columns, data and ajax - if they are provided by one of the properties from above that will override a matching option given here.

Simple example

The most basic example use of DataTables in a Vue application (Composition API) is:

<script setup lang="ts">
import DataTable from 'datatables.net-vue3';

const data = [
  [1, 2],
  [3, 4],
];
</script>

<template>
    <DataTable :data="data" class="display">
        <thead>
            <tr>
                <th>A</th>
                <th>B</th>
            </tr>
        </thead>
    </DataTable>
</template>

You can see this live on Stackblitz.

Ajax data example

You might wish to load data for the table to display via Ajax rather than using local Vue data. That can be done with the ajax parameter directed at the URL to load the data from:

<DataTable
    :columns="columns"
    ajax="/data.json"
    class="display"
    width="100%"
/>

I've shortened the boiler plate code in the above for brevity. This example has the full code and running example including demonstrating how to use object properties to populate the table via the columns.data option.

Extensions example

I showed above how to install and register a DataTables extension. Once they are registered they can be used in the standard DataTables way, through their initialisation options. In this example we initialise the Select extension using the select option:

<DataTable
    :columns="columns"
    :options="{select: true}"
    ajax="/data.json"
    class="display"
    width="100%"
/>

Again for brevity I've shorted the code here, but the full working example can be seen here.

Reactive data

One for the most exciting and useful parts of Vue is Reactive data. In summary this is where you update data (e.g. variable = 1) the UI will automatically update to reflect this change - however complex that change might be. The datatables.net-vue3 package fully supports Vue's reactive data and will automatically reflect the changes made to the data.

To demonstrate that, consider the following:

<button @click="add">Add new row</button><br />
<button @click="update">Update selected rows</button><br />
<button @click="remove">Delete selected rows</button>

<DataTable
    class="display"
    :columns="columns"
    :data="data"
    :options="{ select: true }"
    ref="table"
/>

You will see that we have three buttons which can perform actions on the data array that is bound to the data property. For add() our test function simply looks like:

function add() {
  data.value.push( ... );
}

Note how we don't need to tell DataTables about the new data through any method calls - it just updates automatically.

DataTables API

Update and delete are very similar in that we just manipulate the array of data, but we will need to access the DataTables API to know which rows have been selected by the end user. The DataTable component provides a dt() method that we can use to get this via a Vue reference:

let dt;
const table = ref(); // This variable is used in the `ref` attribute for the component

onMounted(function () {
  dt = table.value.dt();
});

Now to delete a row we can simply get the data for the selected row using row().data(), find it in the array and slice it out:

function remove() {
  dt.rows({ selected: true }).every(function () {
    let idx = data.value.indexOf(this.data());
    data.value.splice(idx, 1);
  });
}

The update process is very similar and is shown in the full working code example.

It is important to note that we do not use the DataTables API methods to manipulate the data here - we just modify the underlying data and it reacts to those changes.

Styling

So far we have a working table, but we want it to look pretty and similar to the other components on our page. Thankfully DataTables' support for various styling libraries is equally easy to use in a Vue application. For example consider that we are using Bootstrap 5 - the rest of our page is Bootstrap 5 style based and our DataTable should reflect that. We have npm packages for DataTables core and all of its extensions that work with Bootstrap 5 (and other styling frameworks) - they end in -bs5 (e.g. datatables.net-bs5 for Bootstrap 5 and DataTables core). The default styling has the -dt postfix. See the download builder to get the styling packages needs for your preferred framework.

With the default styling simply install the styling package:

# npm
npm install --save datatables.net-dt

# yarn
yarn add datatables.net-dt

And then include it in your <style> tag (note that we are using Vite to build the package here, which will resolve CSS styles from node packages as well as Javascript, allowing this to work):

<style>
@import 'datatables.net-dt';
</style>

For the other styling frameworks, you need to also include a Javascript element, which configures DataTables and its extensions to use the styles and DOM structure suitable for the framework selected - e.g. for Bootstrap 5:

# npm
npm install --save datatables.net-bs5

# yarn
yarn add datatables.net-bs5

And in your Vue component register the style in exactly the same way as you do with the extensions:

<script setup lang="ts">
import DataTable from 'datatables.net-vue3';
import DataTableBs5 from 'datatables.net-bs5';

DataTable.use(DataTableBs5);
</script>

<style>
@import 'bootstrap';
@import 'datatables.net-bs5';
</style>

You can see Vue + DataTables + Bootstrap 5 in action here.

Source

The DataTables component for Vue is open source under the MIT license. The source is available on Github.

Feedback

We use Vue extensively in our CloudTables configuration UI and this component builds upon that experience. However, as always, there will be room for improvement! Get in touch with any suggestions and questions that you might have, or even just a little note to say that you are using it, so we can feed that back into our own development and documentation work. The likely next step for this component will be to formalise the documentation in our manual. Stay tuned for that and more.