[Vue] 비동기 async / await 사용하기

양찌·2022년 7월 12일
2

Vue

목록 보기
4/4

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) 를 정리해두었다.

profile
신입 개발자 입니다! 혹시 제 글에서 수정이 필요하거나, 개선될 부분이 있으면 자유롭게 댓글 달아주세요😊

0개의 댓글