vue를 하다보면 비동기로 코드를 처리하고 싶을 때가 있다.
데이터 요청을 비동기 방식으로 처리하여 코드의 순서를 순차적으로 진행하고 싶은 경우가 있다.
user의 모든 post를 불러오기 전까지 로딩 화면이 보였다가, 다 불러와졌으면 로딩화면이 사라지는 코드를 구현해 보자.
이를 위해 async / await 을 사용하여 비동기 처리를 해보자.
// userStore.js
const userStore = {
state : {...},
getters : {...},
mutations : {...},
actions : {
AC_GET_POST_LIST({ commit }, payload) {
return axios
.get(`/post/${payload.userId}`)
.then(res => {
// 여기에서 받아오는 data를 리턴을 해주지 않으면
// 사용하는 곳에서는 padding된 상태의 promise가 최종 받아와짐.
return res.data;
})
.catch(err => alert(err))
}
}
}
// PostList.vue
<template>
... 생략
<div>
// isLoading 값이 true일 때 Loading 컴포넌트가 보임
<Loading v-if="isLoading">
<div> </div>
</div>
</template>
<script>
import Loading from '@/components/common/Loading.vue'
export default {
name : 'post-list',
components : {
Loading
},
created() {...},
data() {
return {
isLoading: false,
postList : []
}
},
methods : {
getPostList : async function () {
// 1. Loading 컴포넌트가 보임
this.isLoading = false;
// 2. 서버로부터 포스트리스트를 가져옴
const postListFromServer = await this.$store.dispatch('userStore/AC_GET_POST_LIST', { userId : 1 });
// 3. Loading 컴포넌트가 없어짐
this.isLoading = true;
}
}
}
</script>
나 같은 경우는 store를 모듈화하여 카테고리 별로 store 파일을 만들었다.
vue는 actions에서 비동기 처리를 하는 메소드를 만든다.
이 포스팅에서 vuex (getters, mutations, actions) 를 정리해두었다.