Vue3 Datatable

repository·main·Indexed 41 days ago

https://github.com/bhaveshpatel200/vue3-datatable

A zero-dependency Vue 3 datatable component supporting client and server-side pagination, sorting, filtering, and row selection. Version 3.0.0 features customizable cell rendering via slots, global search, and a comprehensive API for managing row selection and column configurations.

Tokens
7.1K
Snippets
20
Records
28
Agent score
52%

What's inside Vue3 Datatable

  1. Customize Column Filter Labels

    main

    Use the columnFilterLang prop to provide i18n labels for the various filter conditions available in the column filter dropdown.

    {
        no_filter: 'No filter',
        contain: 'Contain', 
        not_contain: 'Not contain',
        equal: 'Equal', 
        not_equal: 'Not equal',
        start_with: 'Starts with', 
        end_with: 'Ends with',
        greater_than: 'Greater than', 
        greater_than_equal: 'Greater than or equal',
        less_than: 'Less than', 
        less_than_equal: 'Less than or equal',
        is_null: 'Is null', 
        is_not_null: 'Not null',
        all: 'All', 
        true: 'True', 
        false: 'False'
    }
  2. How filtering and sorting work in vue3-datatable

    main

    The library uses a composable-based approach to manage data transformations. When isServerMode is false, the filteredRows computed property automatically applies three layers of transformation in sequence:

    1. Column Filtering: If columnFilter is enabled, it applies filters based on the state of individual columns.
    2. Global Search: It applies a search filter across all columns using the search string.
    3. Sorting: If sortable is enabled, it applies sorting based on the current sortColumn and sortDirection.

    When isServerMode is true, these client-side transformations are bypassed, and the component relies on the totalRows prop for count and expects the server to handle the actual data filtering/sorting logic.

  3. Quickstart: Basic Usage

    main

    To use the datatable, import the component and its CSS, then provide rows and columns props. You can enable features like sorting and column filtering via props.

    <template>
        <vue3-datatable :rows="rows" :columns="cols" :sortable="true" :columnFilter="true"> </vue3-datatable>
    </template>
    
    <script setup lang="ts">
        import { ref } from "vue";
        import Vue3Datatable from "@bhplugin/vue3-datatable";
        import type { IColumnDefinition } from "@bhplugin/vue3-datatable";
        import "@bhplugin/vue3-datatable/dist/style.css";
    
        const cols = ref<IColumnDefinition[]>([
            { field: "id", title: "ID", isUnique: true, type: "number", filter: false },
            { field: "name", title: "Name" },
            { field: "email", title: "Email" },
            { field: "age", title: "Age", type: "number" },
            { field: "dob", title: "Date of Birth", type: "date" },
            { field: "isActive", title: "Active", type: "bool" },
            { field: "address.city", title: "City" },
        ]);
    
        const rows = ref<Array<Record<string, unknown>>>([
            { id: 1, name: "John Doe", email: "john@example.com", age: 28, dob: "1997-05-15", isActive: true, address: { city: "New York" } },
            { id: 2, name: "Jane Smith", email: "jane@example.com", age: 34, dob: "1991-11-22", isActive: false, address: { city: "London" } },
        ]);
    </script>
  4. Implement Server Mode

    main

    To use vue3-datatable in server-side mode (where data fetching, sorting, and filtering are handled by your backend), set the :isServerMode="true" prop and listen to the relevant change events to trigger new API calls.

    Key props for server mode:

    • :isServerMode="true"
    • :loading: Boolean to show loading state
    • :totalRows: Total count of records on the server
    • :pageSize: Current page size
    • :sortable: Enable sorting
    • :columnFilter: Enable column filtering

    Required events to handle:

    • @page-change
    • @page-size-change
    • @sort-change
    • @filter-change
    • @search-change
    • @change-server (Aggregate event containing full state)
    <vue3-datatable
        :rows="rows"
        :columns="cols"
        :loading="loading"
        :totalRows="totalRows"
        :isServerMode="true"
        :pageSize="10"
        :sortable="true"
        :columnFilter="true"
        @page-change="onPageChange"
        @page-size-change="onPageSizeOnSizeChange"
        @sort-change="onSortChange"
        @filter-change="onFilterChange"
        @search-change="onSearchChange"
    />
  5. Handle DataTable events

    main

    The vue3-datatable component emits several events to allow you to react to user interactions and state changes.

    Event Reference

    EventPayloadDescription
    changeServerIServerChangeResponseServer mode only — aggregate event with full state (page, sort, search, filters, change_type)
    pageChangenumberUser clicked pagination button (silent on programmatic resets)
    pageSizeChangenumberPage size dropdown changed
    sortChangeISortChangeResponseColumn sort applied (does NOT reset page)
    filterChangeIColumnDefinition[]Column filter value or condition changed
    searchChangestringGlobal search prop changed
    rowSelectRecord[]Row selection changed (user interaction only)
    rowClickRecordRow single click
    rowDBClickRecordRow double click
    reset-reset() called — only event during reset, all others suppressed

    Event Rules

    • Sorting: Applying a sort does not reset the current page.
    • Resets: When a filter, search, or page size is changed, the table resets to page 1, but it only emits the specific event related to that change (it does not emit pageChange).
    • Pagination: pageChange is only triggered by explicit user clicks on pagination buttons.
    • Resetting: During a reset(), only the reset event (and changeServer if in server mode) is emitted; all other events are suppressed.
  6. Use DataTable methods

    main

    You can interact with the vue3-datatable instance using the following methods to programmatically control state or retrieve data:

    MethodDescription
    reset()Reset all state (selection, filters, search, sort, page)
    getFilteredRows()Returns all filtered rows
    getVisibleRows()Returns current page visible rows
    getColumnFilters()Returns column definitions with current filter state
    getSelectedRows()Returns all selected rows
    clearSelectedRows()Deselect all rows
    selectRow(index)Select row by index
    unselectRow(index)Deselect row by index
    isRowSelected(index)Check if row is selected
  7. Customize pagination arrows and empty states with slots

    main

    The component provides several built-in slots for customizing the UI:

    Pagination Arrows

    Use these slots to change the appearance of the pagination navigation:

    • #firstArrow
    • #previousArrow
    • #nextArrow
    • #lastArrow

    Empty State

    Use the #noData slot to customize the message shown when no rows match the current criteria.

    <template #firstArrow> &laquo; </template>
    <template #previousArrow> &lsaquo; </template>
    <template #nextArrow> &rsaquo; </template>
    <template #lastArrow> &raquo; </template>
    
    <template #noData>
        <div>No records found.</div>
    </template>
  8. Customize cell rendering with slots

    main

    You can customize how specific cells are rendered by using slots named after the field property of your column definitions. This allows you to inject custom HTML or Vue components into specific columns.

    <vue3-datatable :rows="rows" :columns="cols">
        <template #name="{ value }">
            <strong>{{ value.name }}</strong>
        </template>
    </vue3-datatable
  9. Configure Vue3Datatable Props

    main

    The <vue3-datatable> component accepts several props to control its behavior, appearance, and data handling. Key props include:

    • columns (required): Array of IColumnDefinition objects.
    • rows (required): Array of data records.
    • isServerMode: Enables server-side mode (disables client-side sort/filter/pagination).
    • totalRows: Required when isServerMode is true.
    • skin: CSS classes for styling (bh-table-striped, bh-table-hover, bh-table-bordered, bh-table-compact).
    • loading: Shows a loading overlay or skeleton.
    • hasCheckbox: Enables a checkbox column for row selection.
    • search: Global search string.
    • page / pageSize: Controls pagination state.
    • sortable: Enables column sorting.
    • columnFilter: Enables per-column filter inputs.
    • stickyHeader / height: Enables a sticky header with a specific scrollable height.
    • selectRowOnClick: Toggles row selection when a row is clicked.
  10. Define Column Configurations

    main

    Columns are defined using the IColumnDefinition interface. This allows you to control how specific data fields are rendered and interacted with.

    Key properties include:

    • field: The data path (supports dot notation like address.city).
    • title: The text displayed in the header.
    • type: Data type (string, number, date, bool).
    • isUnique: Marks the field as a unique identifier (useful for row selection).
    • filter / search / sort: Boolean flags to enable/disable these features for the specific column.
    • cellRenderer: A function (row) => string for custom cell rendering.
    • html: Boolean to allow raw HTML in the cell.
    • width / minWidth / maxWidth: Controls column sizing.
  11. Configure the Vue3 Datatable Component Props

    main

    The IDataTableProps interface defines the configuration for the <vue3-datatable> component.

    Core Data Props

    • rows: Array of row data objects.
    • columns: Array of IColumnDefinition objects.
    • totalRows: Total row count (required in isServerMode).

    Feature Toggles

    • isServerMode: Enables server-side mode (disables client-side logic).
    • sortable: Enables column sorting globally.
    • columnFilter: Enables per-column filter inputs.
    • pagination: Shows/hides the pagination area.
    • hasCheckbox: Adds a checkbox column for row selection.
    • stickyHeader: Makes the header stay visible during vertical scroll (requires height prop).
    • stickyFirstColumn: Fixes the first column to the left during horizontal scroll.

    Styling and Appearance

    • skin: CSS skin (e.g., 'bh-table-striped', 'bh-table-hover', 'bh-table-bordered', 'bh-table-compact').
    • loading: Shows a loading spinner overlay.
    • rowClass / cellClass: CSS classes for rows/cells. Can be a string, array, or a function (row) => string.
    • columnFilterLang: A Record for i18n of filter condition labels.
    <vue3-datatable
        :rows="data"
        :columns="columns"
        :sortable="true"
        :pagination="true"
        :page-size="20"
        :has-checkbox="true"
        @sort-change="onSort"
        @page-change="onPage"
    />