firebase的配置方法
Danica 1/20/2022 Vue部署
参考资料:
# 步骤:
- 用npm安装firebase
npm install firebase@9.4.1 --save
1
- 在
/src文件夹下新建firebase/firebaseinit.js配置文件,导入firebase
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
1
2
2
- 初始化
Cloud Firestore的实例:
const firebaseApp = initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
const db = getFirestore();
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 导出db
export default db
1
- 打开需要使用的组件文件,例如根组件
App.vue,导入相关模块
import db from "./firebase/firebaseinit"
import { collection, getDocs } from "firebase/firestore";
1
2
3
2
3
- 用
getDocs(collection(db, "集合名"));查询集合collection
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
});
1
2
3
4
2
3
4
- 增加文档(不指定id的情况下,firestore会自动添加)
// Add a new document with a generated id.
const docRef = await addDoc(collection(db, "集合名"), {
name: "Tokyo",//示例字段:‘值’
country: "Japan"//示例字段:‘值’
});
console.log("Document written with ID: ", docRef.id);
1
2
3
4
5
6
2
3
4
5
6
- 修改文档
const newData = doc(db, "集合名", "文档id");
await updateDoc(newData, {
fieldName:value,
});
1
2
3
4
5
2
3
4
5
- 删除文档
import { doc, deleteDoc } from "firebase/firestore";
await deleteDoc(doc(db, "集合名", "文档名"));
1
2
3
2
3
成功获取到数据
