yarn add firebase
src안에 firebase/index.js를 만들고
// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'
const firebaseConfig = {
api어쩌구저쩌구 ㅇㅇㅇ
}
// Initialize Firebase
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
export {
db
}
입력
script setup에서
onMounted(async () => {
const querySnapshot = await getDocs(collection(db, 'todos'))
const fireData = []
querySnapshot.forEach((doc, i) => {
console.log(doc.id, ' => ', doc.data())
const todo = {
id: doc.id,
content: doc.data().content,
done: doc.data().done
}
fireData.push(todo)
})
store.state.db = fireData
})```
store에 저장할때는 이런식으로 데이터를 가져온다.
### firebase에서 실시간으로 데이터를 가져오려면
```js
import { collection, onSnapshot } from 'firebase/firestore'
onSnapshot(collection(db, 'todos'), (querySnapshot) => {
const fireData = []
const cities = []
querySnapshot.forEach((doc) => {
cities.push(doc.data().name)
console.log(doc.id, ' => ', doc.data())
const todo = {
id: doc.id,
content: doc.data().content,
done: doc.data().done
}
fireData.push(todo)
})
store.state.db = fireData
})
위 코드를 셋업에 작성해서 실시간으로 가져올 수 있다.
const newTodoContent = ref('')
const addTodo = () => {
addDoc(collection(db, 'todos'), {
content: newTodoContent.value,
done: false
})
newTodoContent.value = ''
}
newtodoContent는 입력값에 v-model로 데이터바인딩
import { db } from '@/firebase'
import { collection, doc, updateDoc } from "firebase/firestore";
const todosCollectionRef = collection(db, 'todos')
updateDoc(doc(todosCollectionRef, id), {
done: false
}
firebase/index에 다음 내용을 추가하고
import { query, orderBy, limit } from "firebase/firestore";
const todosCollectionQuery = query(todosCollectionRef, orderBy('date', 'desc'))
데이터를 add하는 함수 내부에 date요소를 추가한다.
date: Date.now()
그러면 date요소에 현재시간이 업로드시 같이 추가되는데
이제 get함수에서 collection대신 쿼리를 이용해서 가져오면된다.
onSnapshot(todosCollectionQuery, (querySnapshot) => {
...
}
// limit을 사용해서 쿼리를 가져오는 갯수를 정할 수 있음
const todosCollectionQuery = query(todosCollectionRef, orderBy('date', 'desc'), limit(i))
$ yarn global add firebase-tools
$ firebase login
$ firebase init
o Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys // 선택
참고
$ yarn build
$firebase deploy