VueJS + VUEX + Firebase: Where To Hook Up Firebase?

≡放荡痞女 提交于 2019-11-30 12:09:16

问题


I would like to integrate Firebase in my Vue.JS app.

I wonder WHERE to put the references to Firebase.


回答1:


To install firebase as a dependency in your project cd into your project directory and run the following command in the command line

npm install --save firebase

Now in your main.js file add this

import Vue from 'vue'
import App from './App.vue'
import * as firebase from 'firebase'
import { store } from './store/store'


const config = {
    apiKey: "xxxxxxx",
    authDomain: "xxxxxxx",
    databaseURL: "xxxxxxx",
    storageBucket: "xxxxxxxx",
    messagingSenderId: "xxxxxxx"
  };

firebase.initializeApp(config);
Vue.prototype.$firebase = firebase;

new Vue({
  el: '#app',
  store,
  render: h => h(App)
}) 
  • you can also add your firebase credentials in an external js file and import it in the main.js file as follows:

firebase-config.js

export const config = {
    apiKey: "xxxxxxx",
    authDomain: "xxxxxxx",
    databaseURL: "xxxxxxx",
    storageBucket: "xxxxxxxx",
    messagingSenderId: "xxxxxxx"
  }; 

Now in your main.js do as follows

import Vue from 'vue'
import App from './App.vue'
import * as firebase from 'firebase'
import { store } from './store/store'
import { config } from './firebase-config'

firebase.initializeApp(config);
Vue.prototype.$firebase = firebase;

new Vue({
  el: '#app',
  store,
  render: h => h(App)
}) 
  • adding firebase to the Vue.prototype allows usage of firebase in your vue components by using this.$firebase

  • if you don't want this behavior you can just initialize firebase using firebase.initializeApp(config);

  • now coming to your vuex store you can just import the firebase module as below

    import Vue from 'vue'
    import Vuex from 'vuex'
    import * as firebase from 'firebase'
    
    Vue.use(Vuex);
    
    export const store = new Vuex.Store({
        state:{},
        mutations:{},
        actions:{
            myFirebaseAction: ({commit}) => {
                //you can use firebase like this
                var ref = firebase.database().ref()
            }
        }
    });  
    

Credits to @umang for suggesting to add the firebase global namespace to the Vue.prototype instead of the firebase app instance.



来源:https://stackoverflow.com/questions/44352042/vuejs-vuex-firebase-where-to-hook-up-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!