vue.js/vue.js 2

123. 데이터 로딩 상태 표시 | LoadingSpinner

DEV-Front 2023. 2. 18. 23:36
반응형

1. MainPage.vue

- 로딩 상태위한 data 추가 → isLoading: false, 

- API Data 받기전엔 isLoading: true, 받은 후엔  this.isLoading = false;

- 로딩 스페너 component 가져오기 (import)

- v-if로 isLoading이 true이면 스피너가 보이게 구현완료

<template>
  <div>
    <div class="main list-container contents">
      <h1 class="page-header">Today I Learned</h1>

	  // 5. isLoading이 true이면 스피너가 보이게 구현완료
      <loadingSpinner v-if="isLoading" />
      <ul v-else>
        <postListItem
          v-for="postItem in postsItems"
          :key="postItem._id"
          :postItem="postItem"
        />
      </ul>
    </div>
  </div>
</template>

<script>
import { fetchPosts } from '@/api/index';
import postListItem from '@/components/posts/postListItem.vue';
import loadingSpinner from '@/components/common/LoadingSpinner.vue'; // 4. 로딩 스페너 가져오기

export default {
  components: {
    postListItem,
    loadingSpinner,// 4. 로딩 스페너 가져오기
  },
  data() {
    return {
      postsItems: [],
      isLoading: false, // 1. 로딩 상태위한 data 추가
    };
  },
  methods: {
    async fetchData() {
      this.isLoading = true; // 2. data 받기전엔 true
      const { data } = await fetchPosts();
      this.isLoading = false; // 3. data 받으면 false
      this.postsItems = data.posts;
    },
  },
  created() {
    // 라이프 사이클 훅 컴포넌트 생성 되자마자 데이터 호출
    this.fetchData();
  },
};
</script>

<style>
.post-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.post-contents {
  height: 160px;
  overflow-y: auto;
  font-size: 18px;
}

.post-time {
  position: absolute;
  bottom: 4px;
  right: 5px;
  font-size: 14px;
  color: #9e9e9e;
}
</style>

2. LoadingSpinner.vue

<template>
  <div class="spinner-container">
    <div class="spinner" />
  </div>
</template>

<script>
export default {};
</script>

<style scoped>
.spinner-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 240px;
}
.spinner {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 5px solid #e0e0e0;
  border-bottom: 5px solid #fe9616;
  animation: spin 1s linear infinite;
  position: relative;
}
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

반응형