• This repository has been archived on 24/Oct/2018
  • Stars
    star
    591
  • Rank 75,679 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A straight to the point Vue component to display tables

๐Ÿšจ THIS PACKAGE HAS BEEN ABANDONED ๐Ÿšจ

We don't use this package anymore in our own projects and cannot justify the time needed to maintain it anymore. That's why we have chosen to abandon it. Feel free to fork our code and maintain your own copy or use one of the many alternatives.

A straightforward Vue component to filter and sort tables

Latest Version on NPM Software License Build Status npm


๐Ÿšจ WARNING: FEATURE FREEZE ๐Ÿšจ

Version 1 of this package has become very hard to maintain due to the way it's built up. We also have too many feature requests, which we can't all cater too. We're working on v2 of this package, and won't be adding any new features or accepting feature PR's for v1.


This repo contains a Vue component that can render a filterable and sortable table. It aims to be very lightweight and easy to use. It has support for retrieving data asynchronously and pagination.

Here's an example of how you can use it:

<table-component
     :data="[
          { firstName: 'John', lastName: 'Lennon', instrument: 'Guitar', birthday: '04/10/1940', songs: 72 },
          { firstName: 'Paul', lastName: 'McCartney', instrument: 'Bass', birthday: '18/06/1942', songs: 70 },
          { firstName: 'George', lastName: 'Harrison', instrument: 'Guitar', birthday: '25/02/1943', songs: 22 },
          { firstName: 'Ringo', lastName: 'Starr', instrument: 'Drums', birthday: '07/07/1940', songs: 2 },
     ]"
     sort-by="songs"
     sort-order="asc"
>
     <table-column show="firstName" label="First name"></table-column>
     <table-column show="lastName" label="Last name"></table-column>
     <table-column show="instrument" label="Instrument"></table-column>
     <table-column show="songs" label="Songs" data-type="numeric"></table-column>
     <table-column show="birthday" label="Birthday" data-type="date:DD/MM/YYYY"></table-column>
     <table-column label="" :sortable="false" :filterable="false">
         <template slot-scope="row">
            <a :href="`#${row.firstName}`">Edit</a>
         </template>
     </table-column>
 </table-component>

A cool feature is that the table caches the used filter and sorting for 15 minutes. So if you refresh the page, the filter and sorting will still be used.

Demo

Want to see the component in action? No problem. Here's a demo.

Installation

You can install the package via yarn:

yarn add vue-table-component

or npm:

npm install vue-table-component --save

Next, you must register the component. The most common use case is to do that globally.

//in your app.js or similar file
import Vue from 'vue';
import { TableComponent, TableColumn } from 'vue-table-component';

Vue.component('table-component', TableComponent);
Vue.component('table-column', TableColumn);

Alternatively you can do this to register the components:

import TableComponent from 'vue-table-component';

Vue.use(TableComponent);

Browser Support

vue-table-component has the same browser support as Vue (see https://github.com/vuejs/vue). However, you might need to polyfill the Array.prototype.find method for IE support.

Usage

Here's a simple example on how to use the component.

<table-component
     :data="[
     { firstName: 'John', birthday: '04/10/1940', songs: 72 },
     { firstName: 'Paul', birthday: '18/06/1942', songs: 70 },
     { firstName: 'George', birthday: '25/02/1943', songs: 22 },
     { firstName: 'Ringo', birthday: '07/07/1940', songs: 2 },
     ]"
     sort-by="songs"
     sort-order="asc"
     >
     <table-column show="firstName" label="First name"></table-column>
     <table-column show="songs" label="Songs" data-type="numeric"></table-column>
     <table-column show="birthday" label="Birthday" :filterable="false" data-type="date:DD/MM/YYYY"></table-column>
 </table-component>

This will render a table that is both filterable and sortable. A filter field will be displayed right above the table. If your data contains any html we will filter that out when filtering. You can sort the table by clicking on the column headers. By default it will remember the used filter and sorting for the next 15 minutes.

Props

You can pass these props to table-component:

  • data: (required) the data the component will operate on. This can either be an array or a function
  • show-filter: set this to false to not display the filter field.
  • show-caption: set this to false to not display the caption field which shows the current active filter.
  • sort-by: the property in data on which to initially sort.
  • sort-order: the initial sort order.
  • cache-lifetime: the lifetime in minutes the component will cache the filter and sorting.
  • cache-key: if you use multiple instances of table-component on the same page you must set this to a unique value per instance.
  • table-class: the passed value will be added to the class attribute of the rendered table
  • thead-class: the passed value will be added to the class attribute of the rendered table head.
  • tbody-class: the passed value will be added to the class attribute of the rendered table body.
  • filter-placeholder: the text used as a placeholder in the filter field
  • filter-input-class: additional classes that you will be applied to the filter text input
  • filter-no-results: the text displayed when the filtering returns no results

For each table-column a column will be rendered. It can have these props:

  • show: (required) the property name in the data that needs to be shown in this column.
  • formatter: a function the will receive the value that will be displayed and all column properties. The return value of this function will be displayed. Here's an example
  • label: the label that will be shown on top of the column. Set this to an empty string to display nothing. If this property is not present, the string passed to show will be used.
  • data-type: if your column should be sorted numerically set this to numeric. If your column contains dates set it to date: followed by the format of your date
  • sortable: if you set this to false then the column won't be sorted when clicking the column header
  • sort-by: you can set this to any property present in data. When sorting the column that property will be used to sort on instead of the property in show.
  • filterable: if this is set to false than this column won't be used when filtering
  • filter-on: you can set this to any property present in data. When filtering the column that property will be used to filter on instead of the property in show.
  • hidden: if you set this to true then the column will be hidden. This is useful when you want to sort by a field but don't want it to be visible.
  • header-class: the passed value will be added to the class attribute of the columns th element.
  • cell-class: the passed value will be added to the class attribute of the columns td element.

Listeners

The table-component currently emits one custom event:

  • @rowClick: is fired when a row is clicked. Receives the row data as it's event payload.

Modifying the used texts and CSS classes

If you want to modify the built in text or classes you can pass settings globally. You can use the CSS from the docs as a starting point for your own styling.

import TableComponent from 'vue-table-component';

TableComponent.settings({
    tableClass: '',
    theadClass: '',
    tbodyClass: '',
    filterPlaceholder: 'Filter tableโ€ฆ',
    filterNoResults: 'There are no matching rows',
});

You can also provide the custom settings on Vue plugin install hook:

import Vue from 'vue';
import TableComponent from 'vue-table-component';

Vue.use(TableComponent, {
    tableClass: '',
    theadClass: '',
    tbodyClass: '',
    filterPlaceholder: 'Filter tableโ€ฆ',
    filterNoResults: 'There are no matching rows',
});

Retrieving data asynchronously

The component can fetch data in an asynchronous manner. The most common use case for this is fetching data from a server.

To use the feature you should pass a function to the data prop. The function will receive an object with filter, sort and page. You can use these parameters to fetch the right data. The function should return an object with the following properties:

  • data: (required) the data that should be displayed in the table.
  • pagination: (optional) this should be an object with keys currentPage and totalPages. If totalPages is higher than 1 pagination links will be displayed.

Here's an example:

<template>
   <div id="app">
       <table-component :data="fetchData">
           <table-column show="firstName" label="First name"></table-column>
       </table-component>
   </div>
</template>

<script>
    import axios from 'axios';

    export default {
        methods: {
            async fetchData({ page, filter, sort }) {
                const response = await axios.get('/my-endpoint', { page });

                // An object that has a `data` and an optional `pagination` property
                return response;
            }
        }
    }
</script>

If you for some reason need to manually refresh the table data, you can call the refresh method on the component.

<table-component :data="fetchData" ref="table">
    <!-- Columns... -->
</table-component>
this.$refs.table.refresh();

Formatting values

You can format values before they get displayed by using scoped slots. Here's a quick example:

<table-component
     :data="[
          { firstName: 'John', songs: 72 },
          { firstName: 'Paul', songs: 70 },
          { firstName: 'George', songs: 22 },
          { firstName: 'Ringo', songs: 2 },
     ]"
>

     <table-column label="My custom column" :sortable="false" :filterable="false">
         <template slot-scope="row">
            {{ row.firstName }} wrote {{ row.songs }} songs.
         </template>
     </table-column>
 </table-component>

Alternatively you can pass a function to the formatter prop. Here's an example Vue component that uses the feature.

<template>
    <table-component
        :data="[{ firstName: 'John' },{ firstName: 'Paul' }]">
        <table-column show="firstName" label="First name" :formatter="formatter"></table-column>
    </table-component>
</template>

<script>
export default {
    methods: {
        formatter(value, rowProperties) {
            return `Hi, I am ${value}`;
        },
    },
}
</script>

This will display values Hi, I am John and Hi, I am Paul.

Adding table footer <tfoot> information

Sometimes it can be useful to add information to the bottom of the table like summary data. A slot named tfoot is available and it receives all of the rows data to do calculations on the fly or you can show data directly from whatever is available in the parent scope.

<table-component
    :data="[{ firstName: 'John', songs: 72 },{ firstName: 'Paul', songs: 70 }]">
    <table-column show="firstName" label="First name"></table-column>
    <table-column show="songs" label="Songs" data-type="numeric"></table-column>
    <template slot="tfoot" slot-scope="{ rows }">
        <tr>
            <th>Total Songs:</th>
            <th>{{ rows.reduce((sum, value) => { return sum + value.data.songs; }, 0) }}</th>
            <th>&nbsp;</th>
            <th>&nbsp;</th>
        </tr>
    </template>
</table-component>

OR

<template>
    <table-component
        :data="tableData">
        <table-column show="firstName" label="First name"></table-column>
        <table-column show="songs" label="Songs" data-type="numeric"></table-column>
        <template slot="tfoot">
            <tr>
                <th>Total Songs:</th>
                <th>{{ totalSongs }}</th>
            </tr>
        </template>
    </table-component>
</template>
<script>
export default {
    computed: {
        totalSongs () {
            return this.tableData.reduce(sum, value => {
                return sum + value.songs;
            }, 0);
        }
    },
    data () {
        return {
            tableData: [{ firstName: 'John', songs: 72 },{ firstName: 'Paul', songs: 70 }]
        }
    }
}
</script>

Note: rows slot scope data includes more information gathered by the Table Component (e.g. columns) and rows.data is where the original data information is located.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

yarn test

Contributing

Please see CONTRIBUTING for details.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.

We publish all received postcards on our company website.

Security

If you discover any security related issues, please contact [email protected] instead of using the issue tracker.

Credits

The Pagination component was inspired by this lesson on Laracasts.com.

Support us

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Does your business depend on our contributions? Reach out and support us on Patreon. All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.

License

The MIT License (MIT). Please see License File for more information.

More Repositories

1

laravel-permission

Associate users with roles and permissions
PHP
11,600
star
2

laravel-medialibrary

Associate files with Eloquent models
PHP
5,427
star
3

laravel-backup

A package to backup your Laravel app
PHP
5,337
star
4

laravel-activitylog

Log activity inside your Laravel app
PHP
5,316
star
5

browsershot

Convert HTML to an image, PDF or string
PHP
4,434
star
6

laravel-query-builder

Easily build Eloquent queries from API requests
PHP
3,675
star
7

laravel-analytics

A Laravel package to retrieve pageviews and other data from Google Analytics
PHP
2,948
star
8

image-optimizer

Easily optimize images using PHP
PHP
2,450
star
9

async

Easily run code asynchronously
PHP
2,401
star
10

crawler

An easy to use, powerful crawler implemented in PHP. Can execute Javascript.
PHP
2,400
star
11

laravel-responsecache

Speed up a Laravel app by caching the entire response
PHP
2,248
star
12

data-transfer-object

Data transfer objects with batteries included
PHP
2,220
star
13

laravel-translatable

Making Eloquent models translatable
PHP
2,030
star
14

laravel-sitemap

Create and generate sitemaps with ease
PHP
2,011
star
15

dashboard.spatie.be

The source code of dashboard.spatie.be
PHP
1,940
star
16

laravel-fractal

An easy to use Fractal wrapper built for Laravel and Lumen applications
PHP
1,845
star
17

package-skeleton-laravel

A skeleton repository for Spatie's Laravel Packages
PHP
1,714
star
18

period

Complex period comparisons
PHP
1,618
star
19

laravel-collection-macros

A set of useful Laravel collection macros
PHP
1,602
star
20

laravel-newsletter

Manage Mailcoach and MailChimp newsletters in Laravel
PHP
1,570
star
21

checklist-going-live

The checklist that is used when a project is going live
1,489
star
22

laravel-tags

Add tags and taggable behaviour to your Laravel app
PHP
1,454
star
23

opening-hours

Query and format a set of opening hours
PHP
1,340
star
24

schema-org

A fluent builder Schema.org types and ld+json generator
PHP
1,337
star
25

eloquent-sortable

Sortable behaviour for Eloquent models
PHP
1,268
star
26

laravel-cookie-consent

Make your Laravel app comply with the crazy EU cookie law
PHP
1,268
star
27

laravel-data

Powerful data objects for Laravel
PHP
1,240
star
28

laravel-sluggable

An opinionated package to create slugs for Eloquent models
PHP
1,236
star
29

laravel-settings

Store strongly typed application settings
PHP
1,218
star
30

laravel-searchable

Pragmatically search through models and other sources
PHP
1,217
star
31

pdf-to-image

Convert a pdf to an image
PHP
1,207
star
32

laravel-mail-preview

A mail driver to quickly preview mail
PHP
1,171
star
33

once

A magic memoization function
PHP
1,159
star
34

laravel-honeypot

Preventing spam submitted through forms
PHP
1,134
star
35

laravel-image-optimizer

Optimize images in your Laravel app
PHP
1,121
star
36

laravel-google-calendar

Manage events on a Google Calendar
PHP
1,119
star
37

regex

A sane interface for php's built in preg_* functions
PHP
1,097
star
38

laravel-multitenancy

Make your Laravel app usable by multiple tenants
PHP
1,092
star
39

image

Manipulate images with an expressive API
PHP
1,064
star
40

array-to-xml

A simple class to convert an array to xml
PHP
1,056
star
41

laravel-uptime-monitor

A powerful and easy to configure uptime and ssl monitor
PHP
1,020
star
42

db-dumper

Dump the contents of a database
PHP
987
star
43

laravel-webhook-client

Receive webhooks in Laravel apps
PHP
985
star
44

laravel-model-states

State support for models
PHP
968
star
45

laravel-view-models

View models in Laravel
PHP
963
star
46

simple-excel

Read and write simple Excel and CSV files
PHP
930
star
47

laravel-web-tinker

Tinker in your browser
JavaScript
925
star
48

laravel-webhook-server

Send webhooks from Laravel apps
PHP
920
star
49

calendar-links

Generate add to calendar links for Google, iCal and other calendar systems
PHP
904
star
50

laravel-db-snapshots

Quickly dump and load databases
PHP
889
star
51

laravel-mix-purgecss

Zero-config Purgecss for Laravel Mix
JavaScript
887
star
52

laravel-schemaless-attributes

Add schemaless attributes to Eloquent models
PHP
880
star
53

blender

The Laravel template used for our CMS like projects
PHP
879
star
54

fork

A lightweight solution for running code concurrently in PHP
PHP
863
star
55

laravel-schedule-monitor

Monitor scheduled tasks in a Laravel app
PHP
859
star
56

laravel-menu

Html menu generator for Laravel
PHP
854
star
57

phpunit-watcher

A tool to automatically rerun PHPUnit tests when source code changes
PHP
831
star
58

laravel-failed-job-monitor

Get notified when a queued job fails
PHP
826
star
59

laravel-model-status

Easily add statuses to your models
PHP
818
star
60

form-backend-validation

An easy way to validate forms using back end logic
JavaScript
800
star
61

temporary-directory

A simple class to work with a temporary directory
PHP
796
star
62

laravel-feed

Easily generate RSS feeds
PHP
789
star
63

laravel-event-sourcing

The easiest way to get started with event sourcing in Laravel
PHP
772
star
64

enum

Strongly typed enums in PHP supporting autocompletion and refactoring
PHP
769
star
65

laravel-server-monitor

Don't let your servers just melt down
PHP
769
star
66

laravel-package-tools

Tools for creating Laravel packages
PHP
767
star
67

laravel-tail

An artisan command to tail your application logs
PHP
726
star
68

valuestore

Easily store some values
PHP
722
star
69

laravel-health

Check the health of your Laravel app
PHP
719
star
70

geocoder

Geocode addresses to coordinates
PHP
709
star
71

pdf-to-text

Extract text from a pdf
PHP
707
star
72

ssh

A lightweight package to execute commands over an SSH connection
PHP
696
star
73

menu

Html menu generator
PHP
688
star
74

laravel-url-signer

Create and validate signed URLs with a limited lifetime
PHP
685
star
75

ssl-certificate

A class to validate SSL certificates
PHP
675
star
76

laravel-route-attributes

Use PHP 8 attributes to register routes in a Laravel app
PHP
674
star
77

laravel-validation-rules

A set of useful Laravel validation rules
PHP
663
star
78

laravel-pdf

Create PDF files in Laravel apps
PHP
661
star
79

url

Parse, build and manipulate URL's
PHP
659
star
80

laravel-html

Painless html generation
PHP
654
star
81

laravel-event-projector

Event sourcing for Artisans ๐Ÿ“ฝ
PHP
642
star
82

laravel-server-side-rendering

Server side rendering JavaScript in your Laravel application
PHP
636
star
83

vue-tabs-component

An easy way to display tabs with Vue
JavaScript
626
star
84

macroable

A trait to dynamically add methods to a class
PHP
621
star
85

laravel-blade-javascript

A Blade directive to export variables to JavaScript
PHP
618
star
86

laravel-onboard

A Laravel package to help track user onboarding steps
PHP
616
star
87

laravel-csp

Set content security policy headers in a Laravel app
PHP
614
star
88

laravel-cors

Send CORS headers in a Laravel application
PHP
607
star
89

laravel-short-schedule

Schedule artisan commands to run at a sub-minute frequency
PHP
607
star
90

laravel-translation-loader

Store your translations in the database or other sources
PHP
602
star
91

activitylog

A very simple activity logger to monitor the users of your website or application
PHP
586
star
92

phpunit-snapshot-assertions

A way to test without writing actual testย cases
PHP
584
star
93

http-status-check

CLI tool to crawl a website and check HTTP status codes
PHP
584
star
94

laravel-queueable-action

Queueable actions in Laravel
PHP
584
star
95

ray

Debug with Ray to fix problems faster
PHP
574
star
96

freek.dev

The sourcecode of freek.dev
PHP
571
star
97

server-side-rendering

Server side rendering JavaScript in a PHP application
PHP
568
star
98

string

String handling evolved
PHP
558
star
99

laravel-http-logger

Log HTTP requests in Laravel applications
PHP
538
star
100

laravel-blade-x

Use custom HTML components in your Blade views
PHP
533
star