Make A Sorted and Filtered Table With Vue.JS Quick

Picture shows Jason A. Martin - Software Engineer, Indie Game Developer, Tech Evangelist, Entrepreneur.

If you're looking for a way to make a display table that can be sorted and filtered in Vue.JS, you've come to the right place. Let the games begin!

SETUP

I've created a data object that consists of games along with the price and rating. I want to display this data nicely to the user.

Ah, but the fun doesn't stop there. I want to be able to sort the data by title, price and rating. And I must be able to do it in ASC or DESC order.

But wait! I want more! I want to be able to start typing in a game title in an input field and have my list respond to it. I want the list to filter down as I type.

Sounds like a fun job that should have an LOE of 32,434,234 hours! Just kidding, it's pretty simple to do and I'll show you.

First up will be the example. Feel free to play with it.

Finally, I'll share the code on the bottom of this article.

EXAMPLE

If you want to make your own Vue.js pens, I created a template you can fork here: https://codepen.io/jasonamartin/pen/ZJzKve

SORT OPTIONS

Sorting by: {{ sort }}
{{ name | upper }}
{{ game[title] }}

CODE

new Vue({
  el: '#app',
  data: {
    filterText: '',
    sort: '',
    columns: [ 'title', 'price', 'rating'],
    games: [
      { title: 'Stellaris', price: 44, rating: 8.7},
      { title: 'Crusader Kings 2', price: 32, rating: 8.6},
      { title: 'Battlefront 2', price: 60, rating: 8.3},
      { title: 'Europa Universalis 4', price: 90, rating: 9.5},
      { title: 'Project Gotham', price: 12, rating: 7.1},
      { title: 'Forza 7', price: 65, rating: 8.2},
      { title: 'Mortal Kombat', price: 6, rating: 6.8},
      { title: 'Civilization 4', price: 11, rating: 9.0},
      { title: 'Metroid', price: 35, rating: 8.5},
      { title: 'Hearts of Iron 4', price: 67, rating: 8.1},
      { title: 'MAG', price: 19, rating: 9.8},
      { title: 'Warhawk', price: 27, rating: 9.4},
      { title: 'Fat Princess', price: 34, rating: 7.2},
      { title: 'Ori and the Blind Forest', price: 46, rating: 9},
      { title: 'Destiny 2 Deluxe Edition', price: 99, rating: 8.6},
      { title: 'Super Mario Bros (NES)', price: 4, rating: 8.8},
      { title: 'Zelda', price: 7, rating: 9.2}
    ]
  },
  filters: {
    upper: function(value) {
      return value.toUpperCase();
    }
  },
  methods: {
    sortTable(key, direction){
      this.sort = `${key} > ${direction}`
      if (direction === 'asc') {
        this.games.sort((a, b) => a[key] > b[key] ? 1: -1)
      } else {
        this.games.sort((a, b) => a[key] < b[key] ? 1: -1)
      }
    }
  },
  computed: {
    filteredGames() {
      let filter = new RegExp(this.filterText, 'i')
      return this.games.filter(el => el.title.match(filter))
    }
  }
})