使用Firebase Realtime Database (version 9) 與 Vue 3 建立簡單多人即時聊天室 (一)

Willy
7 min readDec 20, 2022

--

先到Firebase登入,並建立專案

https://console.firebase.google.com/
輸入專案名稱
選擇是否啟用Google Analytics
選擇分析的帳戶
等待建立專案,完成後點選繼續
到此頁面代表完成了,點選紅框處(web建置方案)新增應用程式
輸入應用程式名稱,輸入完後點選註冊應用程式

安裝firebase套件

可以選擇用npm 或 yarn 安裝套件,也可以點選上方script標記,使用cdn的方式載入。

yarn的安裝方式如下:

$ yarn add firebase

接著把圖片下方的config設定貼到專案當中。

const firebaseConfig = {
apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
authDomain: 'chat-room-eae26.firebaseapp.com',
projectId: 'chat-room-eae26',
storageBucket: 'chat-room-eae26.appspot.com',
messagingSenderId: 'xxxxxxxxxxx',
appId: 'xx:xxxxxxxxx:web:xxxxxxxxxxxx',
measurementId: 'X-XXXXXXXXXXX'
}

建立Realtime Database

在專案管理左邊功能欄點選Realtime Database建立資料庫。

點選建立資料庫
選擇資料庫位置
設定安全性規則

安全性規則:因為只是拿來練習可以先選擇以測試模式啟動,測試完就會把專案刪除。但如果以後要作爲正式專案,或預計會一直開著此專案,要記得改為鎖定模式比較安全。

建置完成後會來到此頁面

圖中url為資料庫最外層,firebase資料庫都是採nosql 的json格式。

接著將滑鼠移到url上,就可以設定值,或(點選+)在下層建立資料。

我們就點選+並建立chatroom資料庫。

初始化firebase

接著回到程式中,initializeApp、getDatabase、增加建立資料庫的ref,chatroom就是我們剛剛建立的realtime database。(firebaseConfig 為上方剛建立完應用程式的config

import { initializeApp } from 'firebase/app'
import { getDatabase } from 'firebase/database'
// Initialize Firebase
const app = initializeApp(firebaseConfig)
// Initialize Realtime Database and get a reference to the service
const database = getDatabase(app)
// 建立資料庫ref
const realtimeRef = ref(database, 'chatroom')

監聽firebase realtime database資料

我們到Vue建立component,從firebase/database 中 import onValue方法來監聽資料變化,並在onMounte時執行。(realtimeRef為上方程式碼中的)

import { onValue, DataSnapshot } from 'firebase/database'
onMounted(()=>{
onValue(realtimeRef, (snapshot: DataSnapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val())
}
}, (error) => {
console.error(error)
})
})

接著到後台直接新增資料。

就可以在瀏覽器console中看到,有資料變化時就會接收到。最基本的監聽功能就完成了。

若只想讀取一次則使用下面的方法:

import { ref, get, child } from 'firebase/database'
const dbRef = ref(database)
const getMessage = get(child(dbRef, 'chatroom')).then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val())
} else {
console.log('No data available')
}
}).catch((error) => {
console.error(error)
})

將資料寫入firebase realtime database中

把資料格式設計下面這樣,最上層當key使用time uuix ,裡面的資料分別為:

key:訊息的key(uuid)

message:訊息的內容(string)

time:跟key一樣(time uuix)

username:使用者的暱稱,可以用來區分是自己還是別人(string)

從firebase/database中import set 方法,`chatroom/${dayjs().unix()}` : chatroom為資料庫名稱,${dayjs().unix()}就是上面設計的key。(根據路徑的方式 chatroom 下面的 key)

import { set, ref } from 'firebase/database'
// 寫入 database
const writeUserData = (username: string, message: string) => {
set(ref(database, `chatroom/${dayjs().unix()}`), {
key: uuidv4(),
username,
message,
time: dayjs().unix()
})
}

下面的object就是要寫入的資料。(database為上方程式中初始化的database)

{
key: uuidv4(),
username,
message,
time: dayjs().unix()
}

基本功能都會使用後,就可以開始建立聊天室了

官方文件

--

--

Willy
Willy

Written by Willy

前端修練筆記本,記錄一些踩雷及學習過程,希望能順便幫助一些,在學習或開發路上卡關的人們。

No responses yet