简体   繁体   English

从Web API使用Vue提取数据

[英]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. 我有一个Web API,我正在尝试使用Vue从中获取JSON数据,但是我既没有数据也没有错误,所以我没有什么错。 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 我的HTML

<div id="divContent" class="content">
 {{ content }}
</div>

You appear to already be using jQuery, so to load the Vue when the page is loaded you can update your code to the following: 您似乎已经在使用jQuery,因此要在加载页面时加载Vue,可以将代码更新为以下内容:

$(function(){
  const v = new Vue({
    el: '#divContent',
    created: 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: response => this.serverData = response,
          error: err => alert('Error')
        });
      }
    }
  });  
})

The syntax above is using the jQuery.ready shorthand to create the Vue only after the page is loaded. 上面的语法仅在页面加载后才使用jQuery.ready速记来创建Vue。

Without jQuery, you might want to listen for the DOMContentLoaded event. 如果没有jQuery,则可能需要监听DOMContentLoaded事件。

Alternatively, just load the script that creates the Vue at the bottom of the page and not in the header. 或者,只需在页面底部而不是标题中加载创建Vue的脚本。

Here is a complete, working example. 这是一个完整的可行示例。

 console.clear() $(function(){ const v = new Vue({ el: '#divContent', created: function () { this.loadData(); }, data: { content: 'loading', serverData: null }, methods: { loadData: function (viewerUserId, posterUserId) { $.ajax({ contentType: "application/json", dataType: "json", url: "https://httpbin.org/post", data: JSON.stringify({testing: "some value"}), method: "Post", success: response => { this.content = "loaded" this.serverData = response.json }, error: err => console.log('Error') }); } } }); }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script> <div id="divContent" class="content"> {{ content }} <hr> Response: <br> {{ serverData }} </div> 

Anything your put inside methods: {} won't work unless you call loadData() with @click on the element or when page loads. 您放入的任何methods: {}不起作用,除非您在元素上使用@click或页面加载时调用loadData()

So, you should call it on the element or using either created/mount methods: 因此,您应该在元素上调用它,或者使用创建/装入方法调用它:

So, in your case either do this. 因此,您可以这样做。

<div id="divContent" class="content" @click='loadData'>

or call the method when the page loads as: 或在页面加载为时调用方法:

created () {
 this.loadData()
}

Yes you can use jQuery's $.ajax() API. 是的,您可以使用jQuery的$ .ajax()API。 However, using jQuery just for making Ajax calls is not recommended. 但是,不建议仅将jQuery用于进行Ajax调用。 You don't want to include the whole jQuery library just for the purpose of using Ajax, do you? 您不想仅出于使用Ajax的目的就包括整个jQuery库,是吗? :-) :-)

For Vue.js, you have quite a few options for using Ajax, such as: 对于Vue.js,您有很多使用Ajax的选项,例如:

Here is an example of using the Browser's fetch API . 这是使用浏览器的获取API的示例

HTML 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>

JavaScript 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 产量

在此处输入图片说明

For Loading it on the page load, you can do the following: 要在页面加载时加载它,可以执行以下操作:

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

                },
                error: function () {
                    alert('Error')
                }
            });
        }
    },
    mounted() {
       this.loadData()
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM