๐Ÿ“• Language/Vue

[Age of Vue] Vue.js ์‹œ์ž‘ํ•˜๊ธฐ - 22. ์•ก์‹œ์˜ค์Šค(Axios)

a n u e 2022. 5. 7. 21:13

 

Axios?

Vue์—์„œ ๊ถŒ๊ณ ํ•˜๋Š” HTTP ํ†ต์‹ ์„ ์œ„ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ

 - promise ๊ธฐ๋ฐ˜. API๊ฐ€ ๋‹ค์–‘ํ•˜๋‹ค.

 

(์ฐธ๊ณ  - ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ํŒจํ„ด callback > promise > promise + generator > async & await)


์˜คํ”ˆ API๋ฅผ ์ด์šฉํ•œ axios ํ…Œ์ŠคํŠธ

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Axios</title>
</head>
<body>
  <div id="app">
    <button v-on:click="getData">get user</button>
    <div>
      {{ users }}
    </div>
  </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() { 
          var vm = this;
          axios.get('https://jsonplaceholder.typicode.com/users/')
            .then(function(response) {
              console.log(response.data);
              vm.users = response.data;
            })
            .catch(function(error) {
              console.log(error);
            });
        }
      }
    })
  </script>
</body>
</html>

์ฐธ๊ณ