Simple Example of Fetching & Displaying Remote Data With Vue.JS

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

Odds are that if you're making a Vue.JS web app, you're going to need to pull in data from an API. While there are many ways to do this, here's one fast & easy way to do it that uses Axios to hit an API and display the returned data.

This is a simple Vue.js example that shows how to fetch JSON data from an API on app creation, pass that data into a property and display it. It uses the lifecycle hook "created" to load from the API upon app creation. Not pretty looking, but that's ok.

SETUP

So I want to look up some Magic The Gathering cards and fortunately, they have an API I can use. Who doesn't love cards?

In this example, I hit the API, retrieve the data and display it (yes it's ugly, but hey, it gets the job done). There's one catch. I want to know what cards are RARE so I know what to collect. How can I do this?

Fortunately, Vue.JS makes this cake. Take a look at the example below and look for the purple listings. I've also colored the common, and uncommon cards. :)

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

Magic The Gathering Cards

Loading your data!

{{ card.name }}
{{ card.rarity }}
{{ card.text }}
{{ card.setName }}

CODE

const API = 'https://api.magicthegathering.io/v1/cards?page=5&pageSize=5'

new Vue({
  el: '#app',
  data: {
    magicCards: []
  },
  created() {
    this.loadCards()
  },
  methods: {
    loadCards() {
      axios.get('https://api.magicthegathering.io/v1/cards?page=5&pageSize=10')
        .then(response => {
          const cardData = response.data.cards;
          const cardDataLength = cardData.length;
          for (let index = 0; index < cardDataLength; index++) {
            this.magicCards.push(cardData[index])
          }
        })
    }
  },
  computed: {
    hasCards: function() {
      return (this.magicCards.length <= 0)
    }
  }
})