[Vue] axios
[Vue] axios
서버로 데이터를 요청하려면 (ajax를 요청하려면)
axios 라이브러리를 사용하는 방법과, 기본 fetch 함수쓰는 방법이 있습니다.
fetch
브라우저 기본 기능 비교적 최신 문법이기 때문에 최신 브라우저에서만 이용할 수 있다.
그래서 호환성 문제 때문에 보통은 axios 라이브러리를 사용한다.
axios 라이브러리 설치
1
2
3
npm install axios
or
yarn add axios
axios로 ajax 요청하는 법
ajax 요청하고 싶은 곳에다가 import 한다
1
2
3
4
5
6
7
8
9
10
11
12
(App.vue)
import axios from 'axios'
// get 요청
axios.get()
.then(function(result){
// 요청 성공 시 실행할 코드
})
// post 요청
axios.post()
더보기 버튼을 누르면 데이터를 더 가져오기
- 더보기를 누르면
- 서버에서 추가 게시물을 가져와서
- post로 보여준다!
1
<button @click="more" type="button" class="btn_more">더보기</button>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export default {
name:'App',
data(){
return {
post : post,
}
},
methods: {
more(){
axios.get('https://codingapple1.github.io/vue/more0.json')
.then((result)=>{ // arrow 함수를 쓰면 좋다. (this바인딩 때문)
console.log(result);
});
}
},
components:{
Container,
}
}
받아온 데이터를 기존 post 데이터에 push한다.
1
2
3
4
5
6
7
8
9
10
more(){
axios.get('https://codingapple1.github.io/vue/more0.json')
.then( result => {
this.post.push(result.data);
})
.catch( error =>{
// 요청 실패 시
console.log(error);
})
}
axios post요청
내가 원하는 데이터를 서버에 전달할 수도 있다.
1
2
3
4
5
6
axios.post('URL', {name: 'kim'})
.then(()=>{
// 요청 성공 시
}).catch(()=>{
// 요청 실패 시
})
@숙제
‘더보기’ 버튼으로 aiax를 2번까지만 요청하기
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
33
34
35
export default {
name:'App',
data(){
return {
post : post,
get: 0,
}
},
methods: {
more(){
if( this.get > 1 ){
const btn_more = document.querySelector(".btn_more");
const p = document.createElement("p");
p.innerText = "게시물이 없습니다.";
p.classList.add("no_post");
btn_more.after(p);
btn_more.remove();
return;
}
axios.get(`https://codingapple1.github.io/vue/more${this.get}.json`)
.then( result => {
this.post.push(result.data);
this.get++;
})
.catch( error =>{
// 요청 실패 시
console.log(error);
})
}
},
components:{
Container,
}
}
This post is licensed under CC BY 4.0 by the author.