Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch data with Vue from Web API

I have a Web API and I'm trying to get JSON Data from it by using Vue, but I get neither data or errors, so I don't what is wrong. I want to load the data when the page is loaded.

Here is my code:

const v = new Vue({
    el: '#divContent',
    ready: function () {
        this.loadData();
    },
    data: {
        content: 'loading',
        serverData: null
    },
    methods: {
        loadData: function (viewerUserId, posterUserId) {
            const that = this;
            $.ajax({
                contentType: "application/json",
                dataType: "json",
                url: "http://my-webapi/",
                method: "Post",
                success: function (response) {                        
                    that.$data.serverData = response;

                },
                error: function () {
                    alert('Error')
                }
            });
        }
    }
});

My HTML

<div id="divContent" class="content">
 {{ content }}
</div>
like image 302
Daina Hodges Avatar asked Dec 23 '22 12:12

Daina Hodges


1 Answers

Yes you can use jQuery’s $.ajax() API. However, using jQuery just for making Ajax calls is not recommended. You don’t want to include the whole jQuery library just for the purpose of using Ajax, do you? :-)

For Vue.js, you have quite a few options for using Ajax, such as:

  • Axios
  • vue-resource
  • Browser's built-in fetch API (Using fetch)

Here is an example of using the Browser's fetch API.

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>  
</head>
<body>
  <div id="divContent">
    <h1>Article Search Results</h1>
    <form v-on:submit.prevent="search">
      <input type="text" v-model="query">
      <button type="submit">Search</button>
    </form>

    <ul>
    <li v-for="article in articles" v-bind:key="article.source + article.id">
      {{ article.title }}
    </li>
    </ul>
  </div>
</body>
</html>

JavaScript

const vm = new Vue({
  el: '#divContent',
  data() {
    return {
      query: 'gene',
      articles: 'loading'
    }
  },
  created() {
    this.search();
  },
  methods: {
    search: function () {
      fetch(`https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=${this.query}&format=json`)
        .then(response => response.json())
        .then(json => {
          this.articles = json.resultList.result;
      });
    }
  }
});

Output

enter image description here

like image 170
Yuci Avatar answered Jan 05 '23 04:01

Yuci