<aside> 🐢

1.可能會被收費,需要特別注意

firebase(1/5)-開始使Firebase 2. 前置作業 firebase(2/5)-Cloud Firestore

</aside>

官網教學文件

開始使用 Cloud Firestore  |  Firebase

1.專案目錄檔案架構說明

使用的時候會需要在firebase console介面設定,以及實作在專案中。

以下會針對官方文件範例和chartGPT生成的程式再實作一次,這一篇的程式碼可參考以下commit

  1. https://github.com/ingridkao/firebaseTest2025/commit/6f38e30fd32a65c6cb116f8e05dfe59954a6489f

  2. https://github.com/ingridkao/firebaseTest2025/commit/0eb4f9478a59a9e8b83b99eeb099c5540f0ca170

  3. https://github.com/ingridkao/firebaseTest2025/commit/b28c072eb356737415aafaaf89064259ec46fcc9

    <aside> 🐢

    建議寫的時候把註解拿掉,因為寫的有點太詳細,會影響code閱讀

    第一年去工作的時候,前輩教我要可以「解說」自己在寫什麼,但也是到了第三年才說的出來,總之不要太急想想原子習慣的宗旨。

    </aside>

藍色文字: 以下範例程式碼會使用到的檔案

src/
  **lib/**
    firebase.js          // Firebase 初始化(Modular API)
  **composables/**
    useAuth.js           // 登入、監聽使用者
    useChat.js           // 訊息監聽、送訊息、分頁
  **stores/**
    authStore.js         // 使用者資料
  **components/**
    Chat.vue             // 訊息列表 + 輸入框
  **views/**
    ChatView.vue
  **router/**
    index.js
main.js

2.撰寫firebase讀取寫入邏輯

2-1.基本架構

變數和函式的用途及做什麼,在下方說明

/src/composables/useChat.js,架構如下

import { ref, nextTick } from 'vue'
// firebase/firestore提供的原生方法,需要了解參數和用法需查詢官方文件
import { collection, addDoc, serverTimestamp, query, orderBy, limit, onSnapshot } from 'firebase/firestore'
// 已初始化連線到資料庫
import { db } from '@/lib/firebase'

export function useChat(uidRef) {
  const pageSize = 5
  const messages = ref([])
  const boxRef = ref(null)
  let snapshot = null

  const col = collection(db, 'messages')

  **const listen = () => {}**
  
  **const send = async (text) => {}**

  // 等待 Vue 更新 DOM 後將畫面滾動到底部
  const scrollToBottomSoon = async () => {
    await nextTick()         // 等待 Vue 更新 DOM的方法
    const el = boxRef.value  // 需要綁在組件的div上
    if (el) el.scrollTop = el.scrollHeight
  }

  **// 一進來就監聽
  listen()**

  return { messages, boxRef, send }
}

2-2.撰寫firebase讀取邏輯

1.取得訊息列表-會使用到的狀態和資料

  // 每次僅顯示五筆訊息
  const pageSize = 5

  // 在UI顯示的訊息列表
  const messages = ref([])

  // 儲存從 Firebase Firestore 的 onSnapshot 方法中回傳的快照對象。
  let snapshot = null

  // 指定一個 Firestore 資料庫中的集合(Collection)
  const col = collection(db, 'messages')

2.取得→監聽訊息列表

	const listen = () => {
	  // unsub(): onSnapshot提供的方法,呼叫 unsub() 可以停止監聽
	  // 確認snapshot 已存在才調用
	  if (snapshot) unsub()
	
	  // 先初始化UI上的訊息列表
	  messages.value = []
	
	  // query: 設定查詢條件,篩選並排序資料
	  //  - orderBy:以生成時間作為排序
	  //  - limit: 呈現X筆
	  const q = query(col, orderBy('createdAt', 'desc'), limit(pageSize))
	
	  // onSnapshot方法: 實時監聽資料變化的方法,當資料庫中的資料變更時,會觸發回調並將變更後的資料提供給你。
	  snapshot = onSnapshot(q, snap => {
	    const list = []

	    // 整理快照資料: 因為返回的資料沒有id必須整併
	    snap.forEach(d => list.push({ id: d.id, ...d.data() }))
	
	    // 反轉資料順序:將新訊息顯示在畫面底部
	    messages.value = list.reverse()
	
      // 完成後滑到最下方,如果畫面高度不高可以不用調用
	    scrollToBottomSoon()
	  })

3.一開始就調用這個函數

2-3.撰寫firebase寫入邏輯

1.訊息寫入