programing

웹 API에서 Vue를 사용하여 데이터 가져오기

prostudy 2022. 5. 5. 10:19
반응형

웹 API에서 Vue를 사용하여 데이터 가져오기

웹 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')
                }
            });
        }
    }
});

내 HTML

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

그래, 너는 jQuery의 $.ajax() API를 사용할 수 있어.다만 아약스 전화를 걸기 위해 jQuery를 사용하는 것은 권장하지 않는다.아약스를 이용한다는 목적만으로 jQuery 라이브러리 전체를 포함시키고 싶지는 않으시죠? :-)

Vue.js의 경우 다음과 같이 Ajax를 사용할 수 있는 몇 가지 옵션이 있다.

다음은 브라우저의 가져오기 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>

자바스크립트

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;
      });
    }
  }
});

출력

여기에 이미지 설명을 입력하십시오.

이미 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')
        });
      }
    }
  });  
})

위의 구문은 페이지가 로드된 후에만 Vue를 만들기 위해 속기를 사용하고 있다.

jQuery가 없다면 DOMContent Loaded 이벤트를 듣고 싶을 것이다.

또는 머리글이 아닌 페이지 하단에 Vue를 생성하는 스크립트를 로드하십시오.

여기 완전하고 효과적인 예가 있다.

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>

네가 넣은 것은 무엇이든지methods: {}전화하지 않으면 안 된다loadData()요소를 @클릭하거나 페이지가 로드될 때.

따라서 요소 또는 생성된/마운트 방법을 사용하여 호출하십시오.

그러니까, 당신 같은 경우에는 이렇게 하든지.

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

또는 페이지가 로드될 때 메소드를 다음과 같이 호출하십시오.

created () {
 this.loadData()
}

페이지 로드에 로드하기 위해 다음 작업을 수행하십시오.

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()
    }
});

참조URL: https://stackoverflow.com/questions/47635503/fetch-data-with-vue-from-web-api

반응형