How to fetch JSON data using Vue.js and Axios

in Code Write a comment

In this tutorial, you’ll learn how to quickly fetch remote JSON data in Vue.js.

This approach works for both single page Vue.js applications and Vue.js added to existing project.

First let’s initialize a Vue.js app. In this example we’ll be adding Vue.js to the existing project e.g. WordPress site.

We’ve just loaded Vue.js and Axios library from the CDN.

Now we need to add a <div class="app"></div> to the DOM. This will render Vue.js data inside that div.

The final part is to actually fetch the remote JSON data using Axios. I’ll be using dummy REST API {JSON} Placeholder. See the code below.

var app = new Vue({
  el: "#app",
  data: {
    url: 'https://jsonplaceholder.typicode.com/todos/',
    todos: []
  },
  mounted() {
    axios.get(this.url).then((response) => {
      this.todos = response.data
    })
  }
});

That’s it. We’ve just downloaded our first JSON list. It’s a list of todos. If you want to render, you can do that by adding a moustache code to the DOM like so:

<div id="app">
  <pre>{{ todos }}</pre>
</div>

If you find this post useful, please let me know and share your favourite filters in the comments below.

Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-filter-inside-vue-instance

PS: You can also check how to get the first item in Vue.js arrayhow to add a class to body tag in Vue.jsHow to hide uncompiled mustache {{ code }} in Vue.js, How to use Vue.js filters inside the Vue instance and other Vue.js tutorials.

Write a Comment

Comment