Vue로 PWA 개발 - 그랜파 개발자
마이로그는 여러 사람이 함께 사용하는 웹앱입니다. 나의 마이로그를 따로 모아 보거나, 특정 회원의 마이로그를 모아보고 싶을 때가 있습니다. 회원별 마이로그를 모아볼 수 있는 페이지를 만들어 봅시다.
사용자가 본인이 작성한 글만 모아서 볼 수 있도록 구현하려면, Firestore에서 해당 사용자가 작성한 게시물만 필터링해서 가져오는 기능이 필요합니다. 이를 위해 사용자 인증 정보(예: Firebase Auth)와 Firestore 쿼리를 이용하여 특정 사용자의 게시물만 가져오고, Vue.js에서 해당 게시물을 표시하는 방식으로 구현할 수 있습니다.
Firestore에서는 where 조건을 사용해 특정 필드를 기준으로 문서를 필터링할 수 있습니다. 게시물에 작성자 ID(authorId)를 저장해 두고, where 쿼리로 해당 사용자가 작성한 게시물만 가져오도록 합니다.
Vuex에서 현재 로그인된 사용자의 UID를 가져와, 그 사용자가 작성한 게시물만 Firestore에서 필터링하여 가져오는 액션을 구현합니다.
import { getFirestore, collection, query, where, getDocs } from "firebase/firestore";
import { getAuth } from "firebase/auth";
const db = getFirestore();
const auth = getAuth();
const store = new Vuex.Store({
state: {
userPosts: [], // 본인이 작성한 글 저장
},
mutations: {
setUserPosts(state, posts) {
state.userPosts = posts;
},
},
actions: {
// 현재 사용자가 작성한 게시물 불러오기
async fetchUserPosts({ commit }) {
const user = auth.currentUser;
if (user) {
const userUid = user.uid;
try {
const q = query(collection(db, "posts"), where("authorId", "==", userUid));
const querySnapshot = await getDocs(q);
const posts = [];
querySnapshot.forEach((doc) => {
posts.push({ id: doc.id, ...doc.data() });
});
commit('setUserPosts', posts); // 상태에 저장
} catch (error) {
console.error("본인 글 가져오기 실패:", error);
}
}
},
},
});
export default store;
<template>
<div>
<h3>My Posts</h3>
<v-list v-if="userPosts.length > 0">
<v-list-item v-for="post in userPosts" :key="post.id" @click="goToPostDetail(post.id)">
<v-list-item-content>
<v-list-item-title>{{ post.title }}</v-list-item-title>
<v-list-item-subtitle>{{ post.createdAt.toDate().toLocaleDateString() }}</v-list-item-subtitle>
</v-list-item-content>
</v-list-item>
</v-list>
<p v-else>You haven't written any posts yet.</p>
</div>
</template>
<script>
export default {
computed: {
userPosts() {
return this.$store.state.userPosts;
},
},
methods: {
goToPostDetail(postId) {
this.$router.push({ name: 'PostDetail', params: { postId: postId } });
},
},
mounted() {
this.$store.dispatch('fetchUserPosts'); // 본인 작성 글 가져오기
},
};
</script>
본인이 작성한 게시물 목록을 확인할 수 있는 페이지로 이동할 수 있도록 Vue Router 설정을 추가합니다.
import Vue from 'vue';
import Router from 'vue-router';
import MyPosts from './components/MyPosts.vue';
import PostDetail from './components/PostDetail.vue';
Vue.use(Router);
const routes = [
{
path: '/my-posts',
name: 'MyPosts',
component: MyPosts,
},
{
path: '/post/:postId',
name: 'PostDetail',
component: PostDetail,
props: true,
},
];
export default new Router({
mode: 'history',
routes,
});
게시물 목록이나 사용자 프로필 페이지에서 "내가 작성한 글" 버튼을 추가하여 해당 페이지로 이동할 수 있도록 구현합니다.
<template>
<div>
<h2>User Profile</h2>
<v-btn @click="goToMyPosts">My Posts</v-btn>
</div>
</template>
<script>
export default {
methods: {
goToMyPosts() {
this.$router.push({ name: 'MyPosts' });
},
},
};
</script>
이 방법을 통해 본인이 작성한 글만 모아서 보여주는 기능을 구현할 수 있습니다.