본문 바로가기


프로젝트 하면서/vue

firebase에 데이터 저장하고 불러오기

by worldforest 2020. 8. 12.

채팅을 구현하기 위한 첫 단계

 


 

firebase 설정

index.html
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://apis.google.com/js/platform.js" async defer></script>

 

나머지는 아래 포스팅을 따라하면 기본 설정은 끝이다.

 

 

firebase에서 생성한 프로젝트 정보 가져오기

firebase를 사용한 프로젝트를 시작할 때 필요한 정보를 가져오는 방법을 따로 정리한다. 프로젝트 선택 https://console.firebase.google.com 위의 주소로 들어가서 로그인하면 firebase에서 만든 프로젝트를

worldforest9.tistory.com

 

 

채팅 css와 html 자료
 

HTML Snippets for Twitter Boostrap framework : Bootsnipp.com

Awesome Bootstrap HTML CSS JS Snippet on Bootsnipp.com.

bootsnipp.com

 


 

<teamplate>

messages 배열에 있는 message 하나씩 출력
<div v-for="message in messages" :key="message" class="incoming_msg">
	<div class="incoming_msg_img">
		<img src="https://ptetutorials.com/images/user-profile.png" alt="sunil">
    </div>
	<div class="received_msg">
		<div class="received_withd_msg">
			<p>{{message}}</p>
			<span class="time_date"> {{createdAt}}</span>
		</div>
	</div>
</div>
더보기

createAt은 데이터가 생성된 시간을 보여주기 위해 만들었다. 아직 구현은 못했지만..

 

데이터 보내기
<div class="type_msg">
	<div class="input_msg_write">
		<input @keyup.enter="saveMessage" v-model="message" type="text" class="write_msg" placeholder="Type a message" />
		<button @click="saveMessage" class="msg_send_btn" type="button">
			<i class="fa fa-paper-plane-o" aria-hidden="true"></i>
		</button>
	</div>
</div>

input칸에 입력 후 enter를 누르거나 버튼을 클릭하면 saveMessage 함수가 실행되고 데이터가 저장된다.


<script>

 

data

data(){
	return {
		message: null,
		messages: [],
		createdAt:null,
	}
}

 

 

methods

firebase에 데이터 저장 
 saveMessage(){
	//save to message
		db.collection('chat').add({
		message:this.message,
		createdAt: new Date()
	})
}

 

firebase에서 데이터 가져오기
fetchMessages(){
	db.collection("chat")
	.orderBy('createdAt')
	.onSnapshot( querySnapshot =>{
		let allMessages=[];
		querySnapshot.forEach( doc =>{
			allMessages.push(doc.data().message)
			this.createdAt=new Date()
		});
		this.messages=allMessages
	})
}

 

created

새로운 데이터 입력될 때 마다 가져오기
created(){
	this.fetchMessages();
}

 


 

참고했던 자료

 

 

반응형

댓글