[英]Where to initialize firebase in Vue js app?
// Initialize Firebase
var config = {
apiKey: "...",
authDomain: "my-project.firebaseapp.com",
databaseURL: "https://my-project.firebaseio.com",
projectId: "my-project",
storageBucket: "my-project.appspot.com",
messagingSenderId: "..."
};
firebase.initializeApp(config);
When I initialize Firebase in index.html or main.js, in both cases i have an error当我在 index.html 或 main.js 中初始化 Firebase 时,在这两种情况下我都有一个错误
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
I have to initialize it in my component (Dashboard).我必须在我的组件(仪表板)中初始化它。 Is it proper way to initialize firebase in one of my components?
在我的一个组件中初始化 firebase 是正确的方法吗? Why i can do this in eg main.js ?
为什么我可以在例如 main.js 中做到这一点?
One way is to have a firebaseConfig.js
file like the following 一种方法是使用
firebaseConfig.js
文件,如下所示
import firebase from 'firebase/app';
import 'firebase/firestore';
var config = {
apiKey: "....",
authDomain: ".....",
databaseURL: ".....",
......
};
firebase.initializeApp(config);
const db = firebase.firestore();
// date issue fix according to firebase
const settings = {
timestampsInSnapshots: true
};
db.settings(settings);
export {
db
};
and import and use it in each of your Components (where you need Firebase) as follows: 并在每个组件(您需要Firebase)中导入和使用它,如下所示:
<template>
......
</template>
<script>
const firebase = require('../firebaseConfig.js');
export default {
name: 'xxxxx',
data() {
return {
....
};
},
methods: {
fetchData() {
firebase.db
.collection('xxxxx')
.get()
..... //Example of a call to the Firestore database
}
}
....
};
</script>
So I found that creating an index.js
within a firebase
directory.所以我发现在
firebase
目录中创建一个index.js
。
Then within that file you should set it up with the following:然后在该文件中,您应该使用以下内容进行设置:
import firebase from "firebase/app";
import "firebase/firestore";
import 'firebase/auth';
// firebase init - add your own config here
const firebaseConfig = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: ''
}
firebase.initializeApp(firebaseConfig)
// utils
const db = firebase.firestore()
const auth = firebase.auth()
// collection references
const usersCollection = db.collection('users')
const postsCollection = db.collection('posts')
// export utils/refs
export {
db,
auth,
usersCollection,
postsCollection
}
Then inside of main.js
should be the following然后在
main.js
里面应该是以下内容
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { auth } from './firebase'
let app
auth.onAuthStateChanged(() => {
if (!app) {
app = new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.