firebase的配置方法

1/20/2022 Vue部署

# 步骤:

  1. 用npm安装firebase
npm install firebase@9.4.1 --save
1
  1. /src文件夹下新建firebase/firebaseinit.js配置文件,导入firebase
import { initializeApp } from "firebase/app";  
import { getFirestore } from "firebase/firestore";
1
2
  1. 初始化 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
  1. 导出db
export default db
1
  1. 打开需要使用的组件文件,例如根组件App.vue,导入相关模块
import db from "./firebase/firebaseinit"
import { collection, getDocs } from "firebase/firestore";

1
2
3
  1. getDocs(collection(db, "集合名"));查询集合collection
const querySnapshot = await getDocs(collection(db, "users"));  
querySnapshot.forEach((doc) => { 
	console.log(`${doc.id} => ${doc.data()}`);  
});
1
2
3
4
  1. 增加文档(不指定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
  1. 修改文档
const newData = doc(db, "集合名", "文档id");
await updateDoc(newData, {
  fieldName:value,
});

1
2
3
4
5
  1. 删除文档
import { doc, deleteDoc } from "firebase/firestore";

await deleteDoc(doc(db, "集合名", "文档名"));
1
2
3

成功获取到数据 output

Last Updated: 5/2/2022, 9:10:03 AM