注销时退订Firestore侦听器

时间:2020-03-24 13:36:46

标签: firebase vue.js google-cloud-firestore firebase-authentication nuxt.js

here

说明了实现此目的的简单方法

但是,我很难触发onAuthStateChanged内不同vuex模块中的退订

store / user.js

...
  onAuthStateChanged({ commit, dispatch }, { authUser }) {
    if (!authUser) {
      commit('RESET_STORE')
      this.$router.push('/')
      return
    }
    commit('SET_AUTH_USER', { authUser })
    dispatch('database/getUserItems', null, { root: true })
    this.$router.push('/home')
  }
...

store / database.js

...
getUserItems({ state, commit }, payload) {
    const unsubscribe = this.$fireStore
      .collection('useritems')
      .where('owner', '==', this.state.user.authUser.uid)
      .onSnapshot(
        (querySnapshot) => {
          querySnapshot.forEach(function(doc) {
          // STUFF
        },
        (error) => {
          console.log(error)
        }
      )
  },
...

当用户注销(未定义authUser)时,如何从user.js模块引用unsubscribe()

1 个答案:

答案 0 :(得分:1)

我认为您可以将其保存在Vuex state树中,然后从那里调用它。

  state: {
    //....
    listenerUnsubscribe: null,
    //....
  },
  mutations: {
    //....
    SET_LISTENER_UNSUBSCRIBE(state, val) {
        state.listenerUnsubscribe = val;
    },
    RESET_STORE(state) {
        state.listenerUnsubscribe()
    }
    //....
  },
  actions: {
    //....
    getUserItems({ state, commit }, payload) {
        const unsubscribe = this.$fireStore
        .collection('useritems')
        .where('owner', '==', this.state.user.authUser.uid)
        .onSnapshot((querySnapshot) => {
            querySnapshot.forEach(function(doc) {
            // STUFF
            },
            (error) => {
            console.log(error)
            }
        );
        commit('SET_LISTENER_UNSUBSCRIBE', unsubscribe);
    },