vue.js/vue.js 2

122. 학습 노트 목록 아이템 컴포넌트화 | Props 내려주고 받는 방법

DEV-Front 2023. 2. 13. 00:08
반응형

1. 기존 MainPage.vue

<template>
  <div>
    <div class="main list-container contents">
      <h1 class="page-header">Today I Learned</h1>
      <ul>        
         <li v-for="postsItems in postsItems" :key="postsItems._id">
          <div class="post-title">{{ postsItems.title }}</div>
          <div class="post-contents">{{ postsItems.title }}</div>
          <div class="post-time">{{ postsItems.title }}</div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { fetchPosts } from '@/api/index';

export default {
  data() {
    return {
      postsItems: [],
    };
  },
  methods: {
    async fetchData() {
      const { data } = await fetchPosts();
      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>

1. posts 폴더 생성, 폴더 안에 postListItem.vue 생성


2. MainPage.vue에서 Props 내려주기

<template>
  <div>
    <div class="main list-container contents">
      <h1 class="page-header">Today I Learned</h1>
      <ul>
       // 2. 해당 컴포넌트에 v-for걸어주고 :postItem="postItem" 로 Props 내려주기
        <postListItem
          v-for="postItem in postsItems"
          :key="postItem._id"
          :postItem="postItem"
        />       
      </ul>
    </div>
  </div>
</template>

<script>
import { fetchPosts } from '@/api/index';

// 1. 컴포넌트 import
import postListItem from '@/components/posts/postListItem.vue';

export default {
  components: {
    postListItem, // 2. 컴포넌트 받아오고 
  },
  data() {
    return {
      postsItems: [],
    };
  },
  methods: {
    async fetchData() {
      const { data } = await fetchPosts();
      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>

3. postListItme.vue에서 props 받기

<template>
  <li>
    // 2. props Data 바인딩, Main에서 v-for 해줬기 때문에 여기선 필요없음
    <div class="post-title">{{ postItem.title }}</div>
    <div class="post-contents">{{ postItem.title }}</div>
    <div class="post-time">{{ postItem.title }}</div>
  </li>
</template>

<script>
export default {
  // 1. props 받아주기 
  props: {
    postItem: {
      type: Object, // Data Type 명시
      require: true, 
    },
  },
};
</script>

<style></style>

 

반응형