Home Examples Charts Dashboard Projects Menu

Vue.js examples
Learn Vue.js

vuejs ajax

Related:
Vue: Step-By-Step Guide To Mastering Vue.js From Beginner To Advanced (Vue.js, Learning Vue js 2)

Get data from an API using Ajax?

Ajax requests can be made with the module Axios. Axios is a “promise based HTTP client for the browser and node.js”. In short: get JSON data from API.

vuejs axios example

We get example data formatted in JSON from a dummy API.

  • Create an app that calls a method in the created hook. In this method we call axios.get(url). It returns a response containing your data. Store this data in one of the Vue instance variables.
  • Display the data in a template
new Vue({
el: '#app',
created() {
this.fetchData();
},
data: {
posts: []
},
methods: {
fetchData() {
axios.get('https://jsonplaceholder.typicode.com/posts').then(response => {
this.posts = response.data;
});
}
}
});

The template simply prints out the posts array.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>//vuejsexamples.net</title>
<!-- include vue -->
<script src="//unpkg.com/vue"></script>
<!-- axios -->
<script src="//cdnjs.cloudflare.com/ajax/libs/axios/0.15.3/axios.min.js"></script>
</head>
<body>
<div id="app">
Posts:
<li v-for="post of posts">
<strong>{{post.title}}</strong>
{{post.body}}
</li>
</div>
</body>
<script src="app.js"></script>
</html>

Download Vue.js Examples


← vuejs created vuejs components →

Posts


© vuejsexamples.net - Privacy Policy - Cookie Policy