[Vue] Vuex actions 게시물 더보기 버튼 (feat. ajax)
[Vue] Vuex actions 게시물 더보기 버튼 (feat. ajax)
Vuex에서는 state를 수정할 때 mutations 함수를 만들어서 수정하라고 배워봤는데,
가끔 서버에서 데이터를 가져와서 수정하고 싶을 때가 있다.
그럴때 당연히 서버로 ajax 요청을 날리면 되는데
그런건 mutations에서 직접 하지 않고 actions라는 항목에 적어야 한다.
왜나하면 mutations 함수들을 만들 때 내부에 ajax처럼 오래걸리는 코드를 작성하면
나중에 길게 코드짤 때 힘들어져서 그렇습니다.
1
2
3
4
5
6
(store.js)
...
actions: {
// ajax나 오래걸리는 작업
}
...
더보기 게시물 ajax 요청하기
시간이 소요되는 코드는 actions에 작성한다. (ex ajax)
step
- actions 함수 작성
- mutation 함수 작성
- $store.dispatch(‘actions 함수’)
- actions함수에서 mutation함수를 이용해 state 변경
check 1
- mutation 함수 실행 : $store.commit(‘함수명’, data)
- actions 함수 실행 : $store.dispatch(‘함수명’)
check 2
state 수정은 mutation에서 한다
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
36
37
38
39
40
(store.js)
import { createStore } from "vuex"
import axios from 'axios'
const store = createStore({
state () {
return {
likes: [ 36, 0, 5 ],
isLikes: [false, false, false],
more: [],
}
},
mutations: {
changeLikes(state, data){
state.likes[data] += (state.isLikes[data]) ? -1 : 1;
state.isLikes[data] = !state.isLikes[data]
},
LikesItemShift(state){
state.likes.unshift(0);
state.isLikes.unshift(false);
},
setMore(state, data){
state.more.push(data);
}
},
actions: {
getData(context){
axios.get(`https://codingapple1.github.io/vue/more0.json`)
.then( result => {
context.commit('setMore', result.data); // axios로 가져온 데이터를 mutations setMore을 이용해 저장한다. (저장을 바로 할 수 없기 때문에 commit문을 씀)
})
.catch( error =>{
console.log(error);
})
}
}
})
export default store;
1
2
3
4
5
6
7
8
9
10
(App.vue)
<template>
...
<p>{{ $store.state.more }}</p>
<button @click="$store.dispatch('getData')" type="button" class="btn_more" v-if="tab==0">더보기</button>
</template>
...
This post is licensed under CC BY 4.0 by the author.