2017-09-25 104 views
1

我使用Vue資源將數據從我的web應用程序發佈到firebase。但之後,我發現我需要使用Firebase集成功能在Firebase存儲中上傳IMAGES。所以我整合它在我的src/main.jsVue.Js - Firebase函數不能用於組件

import Vue from 'vue' 
 
import VueResource from 'vue-resource' 
 
import VueRouter from 'vue-router' 
 
import * as firebase from 'firebase' 
 
import App from './App.vue' 
 
import Routes from './routes' 
 

 
Vue.use(VueResource); 
 
Vue.use(VueRouter); 
 

 
const router = new VueRouter({ 
 
    routes: Routes, 
 
    mode: 'history' 
 
}); 
 

 
new Vue({ 
 
    el: '#app', 
 
    render: h => h(App), 
 
    router: router, 
 
    created() { 
 
    firebase.initializeApp({ 
 
     apiKey: 'AIzaSyDhdEhcLPfGqo5_msnhVKWH9BkZNOc6RYw', 
 
     authDomain: 'nots-76611.firebaseapp.com', 
 
     databaseURL: 'https://nots-76611.firebaseio.com', 
 
     projectId: 'nots-76611', 
 
     storageBucket: 'gs://nots-76611.appspot.com' 
 
    }) 
 
    } 
 
})

但是當我試圖在我的組件的方法之一,使用它:

methods: { 
 
    post: function(){ 
 
     //for(var i = 0; i < this.tailors.length; i++){ 
 
     // if(this.$route.params.id == this.tailors[i].id) 
 
     // this.ready_to_wear.tailor_name = this.tailors[i].tName; 
 
     //} 
 
     //this.$http.post('https://nots-76611.firebaseio.com/ready_to_wear.json', this.ready_to_wear); 
 
     let key 
 
     firebase.database().ref('ready_to_wears').push(this.ready_to_wear) 
 
     .then((data) => { 
 
      key = data.key 
 
      return key 
 
     }) 
 
     .then(key => { 
 
      const filename = this.image.name 
 
      const ext = filename.slice(filename.lastIndexOf('.')) 
 
      return firebase.storage().ref('rtws/' + key + '.' + ext).put(this.image) 
 
     }) 
 
     .then(fileData => { 
 
      imageUrl = fileData.metadata.downloadURLs[0] 
 
      return firebase.database().ref('ready_to_wears').child(key).update({rtwImg: imageUrl}) 
 
     }); 
 
    } 
 
}

..它在控制檯日誌中說'firebase' is not defined

我在猜測,雖然將firebase功能集成到了main.js中,但不能在組件中使用firebase功能。如何在組件中使用它?是有它周圍的其他方式?

+0

只需導入它在你需要使用它的任何文件。從'firebase'進口firebase。你沒有將它與vue整合,你只是使用了參考。 'vue-fire'會爲你整合它。 –

回答

2

您似乎沒有使用VueFire,我相信這通過Vue原型屬性將firebase展示爲$ firebase。但是,您可以手動執行此操作。

import Vue from 'vue' 
import VueResource from 'vue-resource' 
import VueRouter from 'vue-router' 
import * as firebase from 'firebase' 
import App from './App.vue' 
import Routes from './routes' 

Vue.prototype.$firebase = firebase 

之後,火力將在 Vue公司或組件爲this.$firebase

methods: { 
    post: function(){ 
     this.$firebase.database().ref() ... etc ... 
    } 
} 
+0

Hi @Bert - 典型的'firebase.initializeApp({})'代碼在哪裏?它會在'Vue.prototype。$ firebase = firebase'之前嗎? – JoeManFoo

+1

@JoeManFoo在大多數情況下,是的,您將初始化Vue之外的Firebase或創建的根Vue的處理程序。以下是來自VueFire的示例:https://github.com/vuejs/vuefire#usage – Bert