반응형
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>
반응형
'vue.js > vue.js 2' 카테고리의 다른 글
124. cookies에 Login정보 저장 | store actions 으로 코드 리팩토링 (0) | 2023.02.19 |
---|---|
123. 데이터 로딩 상태 표시 | LoadingSpinner (0) | 2023.02.18 |
121. Main Page - 학습 노트 조회 API 함수 구현 | v-for로 Data 바인딩 (0) | 2023.02.05 |
120. Request 요청에 Token 넣어서 API 가져오기 | 액시오스 인터셉터 | 인터셉터 모듈화 (0) | 2023.01.24 |
119. 로그아웃 기능 구현 | mutations에 clearUsernmae 함수 추가 (0) | 2023.01.24 |