如何在Firestore中为网络启用离线数据

Luk*_*kas 0 javascript firebase google-cloud-firestore

我想在项目中启用离线数据。我找到了正确的代码,但是我不知道在哪里实现代码

我在firebaseConfig.js文件中实现代码:

import firebase from 'firebase'
import 'firebase/firestore'

// firebase init
// init code goes here
var config = {
 apiKey: '',
 authDomain: '',
 databaseURL: '',
 projectId: '',
 storageBucket: '',
 messagingSenderId: ''
} 
firebase.initializeApp(config)

firebase.firestore().enablePersistence()
 .then(function () {
   // Initialize Cloud Firestore through firebase
   var db = firebase.firestore();
 })
 .catch(function (err) {
   console.log(err)
 })

 // firebase utils
 const db = firebase.firestore()
 const oldRealTimeDb = firebase.database()
 const auth = firebase.auth()
 const currentUser = auth.currentUser

 // date issue fix according to firebase
 const settings = {
   timestampsInSnapshots: true
 }
 db.settings(settings)

 // firebase collections
 const usersCollection = db.collection('users')
 const postsCollection = db.collection('posts')

export {
 db,
 auth,
 currentUser,
 postsCollection,
 usersCollection
Run Code Online (Sandbox Code Playgroud)

}

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import {store} from './store'
import './registerServiceWorker'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css' // Ensure you are using css-loader 
const fb = require('./firebaseConfig.js')

Vue.config.productionTip = false

export const bus = new Vue()

Vue.use(Vuetify)

let app
fb.auth.onAuthStateChanged(user => {
 if (!app) {
  app = new Vue({
   el: '#app',
   store,
   router,
   template: '<App/>',
   components: {
     App
   },
   render: h => h(App)
 }).$mount('#app')
}
})
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Dou*_*son 5

文档中提供的示例代码建议您应调用enablePersistence()并可能在由于某些给定原因而失败的情况下进行记录:

firebase.initializeApp({
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
  projectId: '### CLOUD FIRESTORE PROJECT ID ###',
});

firebase.firestore().enablePersistence()
  .catch(function(err) {
      if (err.code == 'failed-precondition') {
          // Multiple tabs open, persistence can only be enabled
          // in one tab at a a time.
          // ...
      } else if (err.code == 'unimplemented') {
          // The current browser does not support all of the
          // features required to enable persistence
          // ...
      }
  });
Run Code Online (Sandbox Code Playgroud)

调用之后的后续查询enablePersistence()将在内部排队,直到完全完成为止,这意味着查询可能会或可能不会使用本地缓存的数据,具体取决于的结果enablePersistence()。如果能够使用本地持久性对您的应用程序很重要,则您可能希望在执行查询之前等待其结果(触发返回的Promise)。