datatable-vue3-cache
v1.0.2
Published
A datatable caching component
Maintainers
Readme
datatable-vue3-cache
datatable-vue3-cache is a Vue.js component designed for caching and managing datatable data efficiently. It provides a robust solution for handling large datasets with built-in caching mechanisms, built on top of DataTables.net.
Features
- Data Caching: Intelligent caching system for table data with smart cache keys
- Server-side Processing: AJAX data loading with caching optimization
- Advanced Table Features: Sorting, searching, pagination, fixed columns/headers
- Export Capabilities: PDF, CSV, copy with customizable formatting and now excelHtml5, excel
- Performance Optimized: Built-in optimizations for handling large amounts of data
- Cache Management: Methods to append, update, delete, and clear cached data
- Grouping & Totals: Built-in support for grouped data with automatic totals
Installation
npm install datatable-vue3-cache@latestNew Export added
now excelHtml5, excel
Basic Usage
<template>
<DatatableVue3Cache
ref="table"
:options="tableOptions"
:max="9"
:columns="columns"
:ajaxUrl="route('api.data.list')"
:parameters="tableParameters"
@data-loaded="handleDataLoaded"
class="border border-gray-300"
>
<template #table-headers>
<!-- Custom table headers if needed -->
</template>
</DatatableVue3Cache>
</template>
<script setup>
import DatatableVue3Cache from 'datatable-vue3-cache';
import 'datatables.net-dt/css/dataTables.dataTables.css';
const table = ref();
const tableParameters = ref({ category: 'active' });
const handleDataLoaded = (data) => {
console.log('Data loaded:', data);
// Handle the loaded data here
// data contains the response from server or cache
};
const columns = ref([
{ data: 'grade', title: 'Grade', visible: false, type: 'string' },
{ data: 'studentId', title: 'ID', type: 'string', render: (data) => data || '' },
{ data: 'fullName', title: 'FULL NAME', type: 'string', width: '30%', render: (data) => `<span style="white-space:normal">${data}</span>` },
{ data: 'age', title: 'AGE', type: 'string', render: (data) => data || '' },
{ data: 'gender', title: 'GENDER', type: 'string', render: (data) => data || '' },
{ data: 'email', title: 'EMAIL', type: 'string', render: (data) => data || '' },
{ data: 'phone', title: 'PHONE', type: 'string', render: (data) => data || '' },
{ data: 'address', title: 'ADDRESS', type: 'string', render: (data) => data || '' },
{ data: 'gpa', title: 'GPA', type: 'string', render: (data) => data || '' },
{ data: 'status', title: 'STATUS', type: 'string', render: (data) => data || '' },
{
data: 'id',
title: 'Action',
type: 'string',
width: '10%',
render: (data, type, row) => {
return `<button class="edit-btn relative group me-1 text-white bg-blue-600 hover:bg-blue-700 focus:ring-4 focus:ring-blue-200 dark:bg-blue-500 dark:hover:bg-blue-600 dark:focus:ring-blue-700 font-medium rounded-lg text-sm px-2.5 py-1.5" data-id="${data}"><span class="mdi mdi-pencil"></span></button>
<button class="delete-btn relative group me-1 text-white bg-red-600 hover:bg-red-700 focus:ring-4 focus:ring-red-200 dark:bg-red-500 dark:hover:bg-red-600 dark:focus:ring-red-700 font-medium rounded-lg text-sm px-2.5 py-1.5" data-id="${data}"><span class="mdi mdi-trash-can"></span></button>`;
}
}
]);
const tableOptions = {
processing: true,
serverSide: true,
select: true,
responsive: false,
ordering: false,
columnDefs: [
{ targets: [3, 4, 5, 6, 7, 8, 9, 10], className: 'dt-body-left' }
],
lengthMenu: [
{ label: '10', value: 10 },
{ label: '20', value: 20 },
{ label: '50', value: 50 },
{ label: '100', value: 100 },
{ label: '500', value: 500 },
{ label: '1000', value: 1000 }
],
};
</script>
## Component Props
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| `ajaxUrl` | String | No | API endpoint for fetching data |
| `parameters` | Object | No | Additional parameters to send with requests |
| `data` | Array | No | Static data array (when not using AJAX) |
| `options` | Object | No | DataTables configuration options |
| `max` | Number | Yes | Maximum number of columns |
| `columns` | Array | No | Column definitions |
## Exposed Methods
### `reload()`
Refreshes the table display after cache changes. Use this when you've modified the cache data and want to see the updated display:
```javascript
// After updating cache data
table.value.update('studentId', 'ST001', updatedStudent);
table.value.reload(); // Refresh display to show changesclear()
Clears all cache and fetches fresh data from the server. Use this when you want completely new data from the backend:
// Clear all cache and get fresh data from server
table.value.clear();append(newData, sortKeys, specificSort, key)
Adds new data to cache with optional sorting:
// When using columns prop (object-based data)
table.value.append(newRow, ['grade', 'gpa'], {
'grade': ['Freshman', 'Sophomore', 'Junior', 'Senior']
});
// When using template slots (array-based data) - use index position
table.value.append(newRow, [0, 5], { // Sort by index 0 (grade) and 5 (program)
0: ['Freshman', 'Sophomore', 'Junior', 'Senior']
});update(field, value, newRow)
Updates items in cache by field value:
// When using columns prop (object-based data)
table.value.update('studentId', 'ST001', updatedStudent);
// When using template slots (array-based data) - use index position
table.value.update(1, 'ST001', updatedStudent); // Update by index 1delete(field, value)
Removes items from cache:
// When using columns prop (object-based data)
table.value.delete('studentId', 'ST001');
// When using template slots (array-based data) - use index position
table.value.delete(1, 'ST001'); // Delete by index 1Event Handling
Data Loaded Callback
The @data-loaded event fires after data is loaded from the server or cache:
<DatatableVue3Cache
@data-loaded="handleDataLoaded"
// ... other props
/>
const handleDataLoaded = (data) => {
console.log('Data loaded:', data);
// Handle the loaded data here
// data contains the response from server or cache
};Button Click Listeners
const attachButtonListeners = () => {
const tableContainer = document.querySelector('.dataTables_wrapper');
if (!tableContainer) return;
tableContainer.removeEventListener('click', handleTableClick);
tableContainer.addEventListener('click', handleTableClick);
};
const handleTableClick = (event) => {
const target = event.target.closest('.edit-btn, .delete-btn');
if (!target) return;
const id = target.getAttribute('data-id');
if (target.classList.contains('edit-btn')) {
handleEdit(id);
} else if (target.classList.contains('delete-btn')) {
handleDelete(id);
}
};Backend Data Format
The component expects the backend to return data
Format : Object-based Data (Recommended)
{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
{
"DT_RowId": "row_1",
"DT_RowData": { "pkey": 1 },
"grade": "Freshman",
"studentId": "ST001",
"fullName": "John Smith",
"age": "18",
"gender": "Male",
"email": "[email protected]",
"phone": "+1-555-0101",
"address": "123 Main St",
"gpa": "3.8",
"status": "Active"
}
]
}Cache Management
The component automatically generates cache keys based on:
- Pagination (start, length)
- Sorting (column, direction)
- Search terms
- Custom parameters
This ensures efficient data serving and reduces unnecessary API calls.
License
This project is licensed under the MIT License.
Alternative Usage (Without Columns Prop)
You can also use the component without specifying the columns prop by using template slots for headers and column content:
<template>
<DatatableVue3Cache
ref="table"
:ajaxUrl="route('Student.List')"
:options="tableOptions"
:max="7"
class="nowrap"
>
<template #table-headers>
<th>#</th>
<th>Student ID</th>
<th>Name</th>
<th>Gender</th>
<th>Address</th>
<th>Program</th>
<th>Email</th>
<th>Actions</th>
</template>
<template #column-7="{rowData}">
<ButtonCard>
<ButtonNew
types="edit"
color="blue"
tooltips="Profile"
@click="EditList(rowData[7], rowData[0])"
/>
<ButtonNew
types="edit"
color="orange"
tooltips="ShortProfile"
@click="EditList(rowData[7], rowData[0])"
/>
<ButtonNew
types="delete"
tooltips="Delete"
@click="DeleteStudent(rowData[7])"
/>
<ButtonNew
types="edit"
color="blue"
@click="torInfo(rowData[7])"
>
TorInfo
</ButtonNew>
<ButtonNew
types="edit"
icons="mdi mdi-format-list-checkbox"
color="blue"
@click="curriculum(rowData[7])"
>
Curriculum
</ButtonNew>
<LinkCrud
color="blue"
size="sm"
target="_blank"
:Links="route('Student.TOR.Pdf',{StudentID:rowData[7]})"
icons="mdi mdi-file-pdf-box"
>
TOR
</LinkCrud>
</ButtonCard>
</template>
</DatatableVue3Cache>
</template>
<script setup>
const tableOptions = {
processing: true,
serverSide: true,
select: true,
pageLength: 10,
responsive: false,
ordering: false,
fixedColumns: {
rightColumns: 1,
leftColumns: 0
},
lengthMenu: [
{ label: '10', value: 10 },
{ label: '20', value: 20 },
{ label: '50', value: 50 },
{ label: '100', value: 100 },
{ label: '500', value: 500 },
{ label: '1000', value: 1000 }
],
scrollX: true
};
</script>
### Key Differences:
- **No `columns` prop**: Column definitions are handled via templates
- **`#table-headers`**: Define table headers using `<th>` elements
- **`#column-{index}`**: Define custom column content for specific columns
- **`rowData`**: Access row data by index (e.g., `rowData[7]` for column 7)
- **Array-based data**: Backend returns data as arrays instead of objects
### Backend Data Format (Array-based):
```json
{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
["1", "ST001", "John Smith", "Male", "123 Main St", "Computer Science", "[email protected]", "123"],
["2", "ST002", "Jane Doe", "Female", "456 Oak Ave", "Mathematics", "[email protected]", "124"]
]
}