【问题标题】:How to get collection from firestore and set to vuex state when the app is rendered?渲染应用程序时如何从firestore获取集合并设置为vuex状态?
【发布时间】:2018-11-29 06:07:27
【问题描述】:

我有一个名为类别的 Firestore 集合。这个集合中的文档被我的 vue 应用程序中的每个页面(路由)使用,所以我认为访问这些数据的最有效方法是在我的 store.js 中有一个类别状态,这样每个组件都可以访问类别状态当它需要而不是每次从firestore获取它时。渲染应用程序时,如何将类别集合的内容设置为我的 vuex 状态?

这是我的 store.js:

import Vue from 'vue'
import Vuex from 'vuex'
const fb = require('./components/firebase/FirebaseConfig.js')

Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
        categories: []
    },
    actions: {
        fetchCategories({commit, state}) {
            fb.categoriesCollection.get().then((querySnapshot) => {
                if (querySnapshot.empty) {
                    //this.$router.push('/HelloWorld')

                } else {
                    this.loading = false
                    var categories = []
                    querySnapshot.forEach((doc) => {
                        categories.push(doc.data());
                    })

                    this.categories = categories
                }
         })
    },  
    mutations: {
        setCategories(state, val) {
            state.categories = val
        }
    }
})

我知道我可以使用以下方法调用 fetchCategories:

this.$store.dispatch('fetchCategories')

但我不确定该放在哪里。

【问题讨论】:

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


    【解决方案1】:

    可以通过商店内的操作来获取数据。在操作中提交更改以更新状态。

    创建商店后,您可以立即通过调用 store.dispatch 发送 fetch 操作:

    store.js

    import Vue from "vue";
    import Vuex from "vuex";
    const fb = require("./components/firebase/FirebaseConfig.js");
    
    Vue.use(Vuex);
    
    const store = new Vuex.Store({
      state: {
        categories: []
      },
      actions: {
        fetchCategories({ commit }) {
          fb.categoriesCollection.get().then(querySnapshot => {
            if (querySnapshot.empty) {
              //this.$router.push('/HelloWorld')
            } else {
              this.loading = false;
              var categories = [];
              querySnapshot.forEach(doc => {
                categories.push(doc.data());
              });
    
              commit("setCategories", categories);
            }
          });
        }
      },
      mutations: {
        setCategories(state, val) {
          state.categories = val;
        }
      }
    });
    
    store.dispatch("fetchCategories");
    
    export default store;
    

    store应该在声明之外导出

    【讨论】:

      猜你喜欢
      • 2020-04-30
      • 2023-02-13
      • 2019-01-19
      • 2020-04-01
      • 2021-03-03
      • 2020-05-21
      • 1970-01-01
      • 2018-11-29
      • 2019-02-21
      相关资源
      最近更新 更多