用 todoList 來學 Firebase 吧! === ###### tags: `firebase` `六角筆記王` 在firebase直接建立一個專案 ![](https://i.imgur.com/vIpMq5m.png) 進去之後針對自己需要的功能開啟,像是我目前使用realtime databse。 嵌入至應用程式中 --- 當專案建立完成後,可以用npm或是cdn嵌入,只要點擊左邊選單的齒輪專案設定就可以複製需要的程式碼。目前我npm一直失敗,所以先用cdn方式嵌入。 目前我使用readltime database,直接複製上面的程式碼是無法正確執行的,建議進去白框區域連結的`開始使用`。 ![](https://i.imgur.com/V9eL1QY.png) *核心功能的 cdn* ``` <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script> ``` *需要使用登入功能的 cdn* ``` <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script> ``` *Realtime database的 cdn* ``` <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js"></script> ``` 以上三個基本的給他複製到index.html中就對了~ 使用步驟 --- 1.連線資料庫 --- 這裡的`firebaseConfig`就是firebase提供給你的帳號資料,機密資料我就不顯示了😄,把資料庫連線到變數database上面: ``` firebase.initializeApp(firebaseConfig); const database = firebase.database(); ``` 補充一個慘痛經驗,由於本人使用 vue cli & Eslint airbnb,所以cdn放在index.html,使用在vue檔時都會有Eslint的全域偵錯,根據[此篇](https://stackoverflow.com/questions/41552041/global-variables-in-javascript-and-eslint),在eslintric.js 設定中加上:`{globals: {"firebase":"readonly"}}`。 如果針對單篇的可以用:`/* global var1:readonly */` --- 2.與資料庫做互動 --- 以下會透過兩個firebase語法跟資料庫互動: * ref():尋找資料路徑 * set():新增資料 以下來試寫一下,在資料庫中新增筆資料: `database.ref().set('你好');` 注意:`ref()` 的括弧中填寫路徑,而如果沒填寫任何資料就會從根目錄開始查找。 還能新增物件,以下面的為例,先建立一個people物件,同時避免set()把整個根目錄都洗掉,在 `ref()` 設定一個people,在用 `set(物件)` 就會跟其他資料區分開: `firebase.database().ref('people').set(people);` 當然不可能每次都是從根目錄重複複寫資料,所以我們可以先設好一個變數存需要的資料路徑,然後就可以直接對該路徑做push新增資料 ``` const toDosRef = database.ref('toDos'); sendBtn.addEventListener('click',function(){ const temTxt = todoTxt.value; toDosRef.push({'content':temTxt}); }) ``` --- 補充:剛剛提到說用 `.ref('people')` 避免洗掉其他資料,也能使用另外一個語法 `.child()`,像是下面這樣: ``` database.ref().child(people).set({新資料}) ``` 要刪除的話用 `remove()` ``` database.ref().child(people).remove() ``` --- 3.顯示在畫面上 --- 要把資料渲染到畫面,有分成兩種方式: * on:隨時監聽資料庫資料進行渲染 * once:只會渲染一次