Tutorial

Creating a Grid Component with Vue.js

Published on September 5, 2018
Default avatar

By Julia Ihnatova

Creating a Grid Component with Vue.js

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Julia Ihnatova

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Nice!! its vue pure!.. thanks for code

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel