Creating a Grid Component with Vue.js

Julia Ihnatova

There’s a lot of information online about how a modern grid UI component should look like and what features it should provide. One common requirement is for the grid component to be easy to visualize and act on the information.

That’s easy to accomplish using Vue.js and in this article we’ll build a grid component that comprises the following user experience:

  • Fixed Header and with scrollable table body.
  • Pagination between table pages.
  • Ability to change the number of rows per page.

I’ll assume you have Vue.js installed.

Note that the code below is not production-ready and is presented here for educational purposes.

The Code

The code below is a modified example taken from the official Vue.js documentation.

Create a new single-file component, Grid.vue, with the following code:

Grid.vue

<div class="wrapper">
  <form id="search">
    Search <input name="query" v-model="searchQuery">
  </form>
  <div id="grid-template">
    <div class="table-header-wrapper">
      <table class="table-header">
        <thead>
          <th v-for="key in columns"
            @click="sortBy(key)"
            :class="{ active: sortKey == key }"
          >
            {{ key | capitalize }}
            <span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'"></span>
          </th>
        </thead>
      </table>
    </div>
    <div class="table-body-wrapper">
      <table class="table-body">
        <tbody>
          <tr v-for="entry in filteredData">
            <td v-for="key in columns"> {{entry[key]}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>
export default {
  name: "grid",
  props: {
    data: Array,
    columns: Array,
  },
  data(){
    return {
      searchQuery: '',
      sortKey: '',
      sortOrders: {},
    }
  },
  computed: {
    filteredData: function () {
      let sortKey = this.sortKey;
      let filterKey = this.searchQuery && this.searchQuery.toLowerCase();
      let order = this.sortOrders[sortKey] || 1;
      let data = this.data;

      if (filterKey) {
        data = data.filter(function (row) {
          return Object.keys(row).some(function (key) {
            return String(row[key]).toLowerCase().indexOf(filterKey) > -1;
          })
        })
      }
      if (sortKey) {
        data = data.slice().sort(function (a, b) {
          a = a[sortKey];
          b = b[sortKey];
          return (a === b ? 0 : a > b ? 1 : -1) * order;
        })
      }
    return data;
    },
  },
  filters: {
    capitalize: function (str) {
      return str.charAt(0).toUpperCase() + str.slice(1);
    }
  },
  methods: {
    sortBy: function (key) {
      this.sortKey = key;
      this.sortOrders[key] = this.sortOrders[key] * -1
    },
  },
  created(){
    let sortOrders = {};
    this.columns.forEach(function (key) {
      sortOrders[key] = 1;
    })
    this.sortOrders = sortOrders;
  }
}
body{
  font-family: Helvetica Neue, Arial, sans-serif;
  font-size: 14px;
  color: #555;
}

table {
  border-spacing: 0;
  width: 100%;

}

th {
  background-color: #008f68;
  color: rgba(255,255,255,0.66);
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

td {
  border-bottom: 1px #008f68 solid;
}

th, td {
  min-width: 150px;
  padding: 10px 20px;
}

th.active {
  color: #fff;
}

th.active .arrow {
  opacity: 1;
}

.arrow {
  display: inline-block;
  vertical-align: middle;
  width: 0;
  height: 0;
  margin-left: 5px;
  opacity: 0.66;
}

.arrow.asc {
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-bottom: 4px solid #FAE042;
}

.arrow.dsc {
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 4px solid #FAE042;
}

#grid-template {
  display: flex;
  display: -webkit-flex;
  flex-direction: column;
  -webkit-flex-direction: column;
  width: 600px;
}

Now import this component to your App.vue file and add some data:

App.vue

import Grid from './Grid'
export default {
  name: 'app',
    data() {
      return {
        gridData: [
          { name: 'American alligator', location: 'Southeast United States' },
          { name: 'Chinese alligator', location: 'Eastern China' },
          { name: 'Spectacled caiman', location: 'Central & South America' },
          { name: 'Broad-snouted caiman', location: 'South America' },
          { name: 'Jacaré caiman', location: 'South America' },
          { name: 'Black caiman', location: 'South America' },
        ],
        gridColumns: ['name', 'location'],        
      }
  },
  components: {
    Grid
  }
}

Use the component by passing the corresponding data:

<grid :data="gridData" :columns="gridColumns"></grid>

Next let’s extend this component with the additional functionality we talked about in the introduction.

Fixed Header

I’m using a technique from the article The Holy Grail: Pure CSS Scrolling Tables with Fixed Headers and the markup is already setup according to this article. Define a height for the table and make table body scrollable:

.wrapper{
  height: 300px;
}

#grid-template > .table-body-wrapper {
  width: 100%;
  overflow-y: scroll;
}

#grid-template {
  height: 100%;
}

#grid-template > .table-body-wrapper {
  flex: 1;
}

Pagination

First let’s define the number of rows per page, and the start position. For this will add two new properties:

startRow: 0,
rowsPerPage: 10

Let’s add the markup for the navigation that shows the current page number:

<div id="page-navigation">
  <button>Back</button>
  <p>{{startRow / rowsPerPage + 1}} out of {{Math.ceil(filteredData.length / rowsPerPage)}}</p>
  <button>Next</button>
</div>

To change between pages add click events handler for our buttons. @click=movePages(-1) for the Back button and @click=movePages(1) for the Next button.

This method will count the number of rows that is first on the page:

movePages: function(amount) {
  let newStartRow = this.startRow + (amount * this.rowsPerPage);
  if (newStartRow >= 0 && newStartRow < this.filteredData.length) {
    this.startRow = newStartRow;
  }
}              

Now add a computed property that will filter and return the rows for the current page:

dataPerPage: function() {
  return this.filteredData.filter((item, index) => index >= this.startRow && index < (this.startRow + this.rowsPerPage))
}

We now have to display updated data, since we’re able to move between pages. Change .table-body from filteredData to dataPerPage:

<tr v-for="entry in dataPerPage">
  <td v-for="key in columns"> {{entry[key]}}</td>
</tr>

Length Selection

To allow to set the number of rows add a simple select with v-model equal to the rowsPerPage property.

For options we will set the pageSizeMenu property to an array with number values:

pageSizeMenu: [10, 20, 50, 100]
<select v-model="rowsPerPage">
  <option v-for="pageSize in pageSizeMenu" :value="pageSize">{{pageSize}}</option>
</select>

And this is all you need to have the ability to change the number of rows per page. Vue will do the rest of the work, thanks to two-way data binding.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#