使用 Vue 从 Web API 获取数据

Dai*_*ges 4 javascript vue.js vuejs2

我有一个 Web API,我正在尝试使用 Vue 从中获取 JSON 数据,但是我既没有得到数据也没有得到错误,所以我不知道有什么问题。我想在加载页面时加载数据。

这是我的代码:

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')
                }
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

我的 HTML

<div id="divContent" class="content">
 {{ content }}
</div>
Run Code Online (Sandbox Code Playgroud)

Yuc*_*uci 7

是的,您可以使用 jQuery 的 $.ajax() API。但是,不建议仅使用 jQuery 进行 Ajax 调用。您不想为了使用 Ajax 的目的而包含整个 jQuery 库,是吗?:-)

对于 Vue.js,您有很多使用 Ajax 的选项,例如:

这是使用浏览器的 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/vue@2.5.16/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>
Run Code Online (Sandbox Code Playgroud)

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;
      });
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

输出

在此处输入图片说明