Vue – ajax

Get data from server

This is one of topic of javascript framework.
We understand how to manage data and change data with Vue object.
Next step is, to get data from servers.

axios

In Vue documentation, axios is introduced as example.
axios is Promise based HTTP client for the browser and node.js.

How to test?

Do we need server side program? No, we can prepare json-server to provide json response.
Install json-server

npm install json-server -g

(Global install, we can use json-server command)
I prepared json data into project.

{
  "data" : [
    {"title": "the very first post", "abstract": "lorem ipsum some test dimpsum"},
    {"title": "and then there was the second", "abstract": "lorem ipsum some test dimsum"},
    {"title": "third time's a charm", "abstract": "lorem ipsum some test dimsum"},
    {"title": "four the last time", "abstract": "lorem ipsum some test dimsum"}
  ]
}

Done. Next, we can start json-server

json-server --watch data.json

We can access http://localhost:3000/data and receive json response.
If you want to know more, please read json-server

Sample

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css">
    <title>The greatest news app ever</title>
  </head>
  <body>
    <div class="container" id="app">
      <h3 class="text-center">VueNews</h3>
      <div class="columns medium-3" v-for="result in results">
        <div class="card">
          <div class="card-divider">
            {{ result.title }}
          </div>
          <div class="card-section">
            <p>{{ result.abstract }}.</p>
          </div>
        </div>
      </div>
    </div>
    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="app.js"></script>
  </body>
</html>

app.js

const vm = new Vue({
  el: '#app',
  data: {
    results: [
      /*
      {title: "the very first post", abstract: "lorem ipsum some test dimpsum"},
      {title: "and then there was the second", abstract: "lorem ipsum some test dimsum"},
      {title: "third time's a charm", abstract: "lorem ipsum some test dimsum"},
      {title: "four the last time", abstract: "lorem ipsum some test dimsum"}*/
    ]
  },
  mounted() {
    axios.get("http://localhost:3000/data")
    .then(response => {
      this.results = response.data;
    }).catch( error => {
      console.log(error);
    });
  }
});