Vue로 PWA 개발 - 그랜파 개발자
mylog는 제목과 내용을 씁니다. 작성일은 저장하면서 자동으로 입력이 되고, 마이로그 보기 기능을 구현할 때 조회수나 구독을 위하여 DB가 변경될 것입니다. 우선 간단하게 시작합니다.
To create a writing screen with a title and content input fields using Vuetify's card view and save the written text to Firestore, follow these steps:
Firestore에 작성한 텍스트를 저장하고 Vuetify의 카드 뷰를 사용하여 제목과 내용 입력 필드가 있는 작성 화면을 만들려면 다음 단계를 따르세요
Set Up Firebase Firestore in Your Vue Project: Ensure you have Firebase and Firestore set up correctly.
프로젝트에서 Firebase Firestore 설정: Firebase와 Firestore가 올바르게 설정되었는지 확인합니다.
Create a Vue Component Using Vuetify Card for Writing: Use Vuetify's v-card to structure the writing screen.
작성 용으로 Vuetify 카드 뷰를 사용하는 Vue 컴포넌트 만들기: Vuetify의 v-card를 사용하여 작성 화면을 만듭니다.
Implement a Function to Save Data to Firestore: Use Firestore methods to save the input data.
Firestore에 데이터를 저장하는 함수 구현: Firestore 메서드를 사용하여 입력 데이터를 저장합니다.
First, install Firebase if you haven't done so:
먼저, Firebase가 설치되지 않았다면 설치하세요:
npm install firebase
Next, initialize Firebase and Firestore in your project. You can do this in a firebase.js file.
그다음, 프로젝트에서 Firebase와 Firestore를 초기화합니다. 이를 위한 firebase.js 파일을 생성할 수 있습니다.
// src/firebase.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// Your Firebase configuration
const firebaseConfig = {
apiKey: process.env.VUE_APP_FIREBASE_API_KEY,
authDomain: process.env.VUE_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.VUE_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.VUE_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.VUE_APP_FIREBASE_APP_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app); // Initialize Firestore
export { db };
Now, create a Vue component named WritingScreen.vue that uses Vuetify’s v-card to create a writing screen.
이제 WritingScreen.vue라는 이름의 Vue 컴포넌트를 만들고 Vuetify의 v-card를 사용하여 작성 화면을 만듭니다.
<template>
<v-container>
<v-row justify="center">
<v-col cols="12" md="8">
<v-card>
<v-card-title>
<span class="text-h5">Create a New Post</span>
</v-card-title>
<v-card-text>
<v-form @submit.prevent="savePost">
<v-text-field
v-model="title"
label="Title"
required
></v-text-field>
<v-textarea
v-model="content"
label="Content"
rows="10"
required
></v-textarea>
<v-btn type="submit" color="primary">Save</v-btn>
</v-form>
</v-card-text>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<script>
import { db } from "../firebase"; // Import Firestore instance
import { collection, addDoc, serverTimestamp } from "firebase/firestore"; // Firestore functions
export default {
data() {
return {
title: "",
content: "",
};
},
methods: {
async savePost() {
if (!this.title || !this.content) {
alert("Please fill in both fields.");
return;
}
try {
await addDoc(collection(db, "posts"), {
title: this.title,
content: this.content,
createdAt: serverTimestamp(),
});
alert("Post saved successfully!");
this.title = "";
this.content = "";
} catch (error) {
console.error("Error adding document: ", error);
alert("There was an error saving the post.");
}
},
},
};
</script>
<style scoped>
.text-h5 {
font-weight: bold;
}
</style>
Here’s what each part of the WritingScreen.vue component does:
WritingScreen.vue 컴포넌트의 각 부분에 대한 설명:
Uses Vuetify’s v-container, v-row, and v-col for layout.
Vuetify의 v-container, v-row, v-col을 사용하여 레이아웃을 구성합니다.
v-card, v-card-title, and v-card-text create the card layout for the form.
v-card, v-card-title, v-card-text를 사용하여 폼의 카드 레이아웃을 만듭니다.
v-text-field and v-textarea provide input fields for the title and content.
v-text-field와 v-textarea는 제목과 내용을 입력할 수 있는 필드를 제공합니다.
v-btn is used to submit the form.
v-btn은 폼 제출을 위해 사용됩니다.
Imports Firestore functions and initializes the component's data properties.
Firestore 함수를 가져와서 컴포넌트의 데이터 속성을 초기화합니다.
savePost method:
savePost 메서드
Ensure to register and include the WritingScreen component in your main application file or router setup.
WritingScreen 컴포넌트를 메인 애플리케이션 파일이나 라우터 설정에 등록하고 포함해야 합니다.
<!-- src/App.vue -->
<template>
<v-app>
<WritingScreen />
</v-app>
</template>
<script>
import WritingScreen from "./components/WritingScreen.vue"; // Import the component
export default {
components: {
WritingScreen,
},
};
</script>
Make sure your Firestore rules allow write access during development. For production, you should set more restrictive rules.
개발 중에는 Firestore 규칙이 쓰기 액세스를 허용하는지 확인하세요. 프로덕션 환경에서는 더 제한적인 규칙을 설정해야 합니다.
Example of a basic Firestore rule:
기본적인 Firestore 규칙의 예:
service cloud.firestore {
match /databases/{database}/documents {
match /posts/{postId} {
allow read, write: if request.auth != null; // Allows authenticated users to read/write
}
}
}
This guide walks you through creating a Vue component using Vuetify's card layout to create a writing screen. The screen allows users to input a title and content, which is then saved to Firestore. The example demonstrates form handling, Firestore interaction, and basic error handling.
이 가이드는 Vuetify의 카드 레이아웃을 사용하여 Vue 컴포넌트를 만들고 작성 화면을 만드는 방법을 설명합니다. 사용자가 제목과 내용을 입력할 수 있으며, 입력한 내용은 Firestore에 저장됩니다. 이 예제는 폼 처리, Firestore 상호작용, 기본 오류 처리 방법을 포함하고 있습니다.