如何从我的vuex动作中分离Firestore侦听器?

时间:2018-08-29 04:47:56

标签: javascript firebase vue.js google-cloud-firestore vuex

我正在使用Firestore来获取我的vuex存储中的已保存数据。例如,当我注销时,我不太了解如何分离监听器。

fetchExercises ({commit, getters}) {
  const db = firebase.firestore()
  const exercises = db.collection('exercises').where('userId', '==', getters.user.uid)

  // Getting Real time feeds
  exercises.onSnapshot(querySnapshot => {
    commit('setLoading', true)
    let source = querySnapshot.metadata.hasPendingWrites ? 'Local' : 'Server'

    console.log(`Source ${source}`)
    if (querySnapshot) {
      querySnapshot.forEach(doc => {
        commit('watchExercises', {
          title: doc.data().title,
          language: doc.data().language,
          translated: doc.data().translated,
          lastOpen: doc.data().lastOpen,
          dueDate: doc.data().dueDate,
          uid: doc.data().uid,
          userId: doc.data().userId,
          words: doc.data().words,
          shared: false
        })
        const exercise = {
          title: doc.data().title,
          uid: doc.data().uid,
          lastOpen: doc.data().lastOpen,
          language: doc.data().language,
          translated: doc.data().translated,
          dueDate: doc.data().dueDate,
          words: doc.data().words,
          shared: false
        }
        commit('updateExercises', exercise)
      })
    }
    if (querySnapshot.size === getters.loadedExercises.length) {
      commit('setLoading', false)
    }
  })
}

这是获取数据的操作,所以现在我想知道如何在另一个操作中分离侦听器?就像退出操作一样。

1 个答案:

答案 0 :(得分:1)

this.unsubscribe = this.exercises.onSnapshot(
    // your code
);

// Stop listening to changes
// Call this when a user is signed out for example

this.unsubscribe();

More info About it