IT/development

[Vue.js] ajax api ํ˜ธ์ถœ(feat. axios)

์•Œ ์ˆ˜ ์—†๋Š” ์‚ฌ์šฉ์ž 2023. 7. 27.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <div id="app">
				<!-- getData()๋ผ๋Š” ํด๋ฆญ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ -->
        <button @click="getData">get users</button>
				<!-- users์˜ ๋ฐ์ดํ„ฐ๊ฐ€ ๋ณ€๊ฒฝ๋˜๋ฉด ๋ฐ›์•„์˜จ ๋ฐ์ดํ„ฐ๋กœ ํ‘œ์‹œ๋จ -->
        <div>{{ users }}</div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
		<!-- axios import -->
    <script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>
    <script>

        new Vue({
            el: '#app',
            methods: {
                //๋ฒ„ํŠผ ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ 
                getData: function() {
										//Vue ์ธ์Šคํ„ด์Šค๋ฅผ ๋ณ€์ˆ˜์— ์น˜ํ™˜	
                    let vm = this;
										//axios์—์„œ https://jsonplaceholder.typicode.com/users์„ get์œผ๋กœ ํ˜ธ์ถœ
                    axios.get('https://jsonplaceholder.typicode.com/users/')                        
												//์„ฑ๊ณต ์‹œ ๋กœ์ง  		
                        .then(function(response) {
                            console.log(response.data);
													  //api์—์„œ ๋ฐ›์•„์˜จ ๊ฒฐ๊ณผ๋ฅผ ์ธ์Šคํ„ด์Šค์˜ data์ธ users์— ์น˜ํ™˜
                            vm.users = response.data;
                        })
											  //์‹คํŒจ ์‹œ
                        .catch(function(error) {
                            console.log(error);
                        });
                }
            },
            data: {
                users: []             
            },
        });
    </script>


</body>
</html>

๊ฒฐ๊ณผ

๋Œ“๊ธ€