뷰에서 권고하는 HTTP 통신 라이브러리는 액시오스(Axios)입니다. Promise 기반의 HTTP 통신 라이브러리이며 상대적으로 다른 HTTP 통신 라이브러리들에 비해 문서화가 잘되어 있고 API가 다양합니다.


CDN

1
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
cs


npm

1
npm install axios
cs


json User샘플데이터

https://jsonplaceholder.typicode.com/users/



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<body>
    <div id="app">
        <!-- 버튼을 클릭했을때 getData 메서드를 호출한다. -->
        <button @click="getData">get user</button>
    </div>
 
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    
    <script>
        new Vue({
      el: '#app',
      data: {
        users: []
      },
      methods: {
        getData: function() { 
          axios.get('https://jsonplaceholder.typicode.com/users/')
            //then = 성공하면 실행
            .then(function(response) {
              console.log(response.data);
              this.users = response.data;
            })
            // catch = 실패하면 실행
            .catch(function(error) {
              console.log(error);
            });
        }
      }
    })
    </script>
</body>
cs


get user버튼을 클릭하면 유저리스트를 가지고 온다.




버튼을 눌렀을 때 콘솔에 데이터가 호출되지만 

this.users = response.data; 가 들어가지 않는다.


getData메서드 기준으로 this가 위에 있냐 밑에 있냐에 따라 다르게 적용된다.


아래처럼 처리해주면 버튼을 눌렀을때 유저의 값을 가져온다.




'Vue' 카테고리의 다른 글

이벤트 처리  (0) 2019.08.02
디렉티브  (0) 2019.08.02
뷰리소스  (0) 2019.08.02
네스티드 라우터(Nested Router), 네임드 뷰(Named View)  (0) 2019.08.02
뷰 라우터  (0) 2019.08.01

+ Recent posts