呈现应用程序时,如何从Firestore获取集合并将其设置为vuex状态? [英] How to get collection from firestore and set to vuex state when the app is rendered?
问题描述
我有一个名为category的Firestore集合.我的Vue应用程序中的每个页面(路线)都使用此集合中的文档,因此我认为访问此数据的最有效方法是在store.js中具有类别状态,以便每个组件都可以访问类别状态需要时,而不是每次都从firestore中获取时.呈现应用程序后,如何将Categories集合的内容设置为vuex状态?
I have a firestore collection called categories. The documents in this collection are used by every page (route) in my vue application so I figured that the most efficient way to access this data would be to have a categories state in my store.js such that each component can access the categories state when it needs to instead of getting it from firestore each time. How would I set the contents of the categories collection to my vuex state when the application is rendered?
这是我的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')
但是我不确定该放在哪里.
but I am unsure where to put this.
推荐答案
可以通过商店内部的操作来获取数据.在操作中,提交更改以更新状态.
The data can be fetched with an action inside the store. within the action commit the changes to update the state.
创建商店后,您可以通过调用store.dispatch
立即分派获取操作:
Once your store is created, you can immediately dispatch the fetch action by calling store.dispatch
:
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;
商店应与声明分开导出
这篇关于呈现应用程序时,如何从Firestore获取集合并将其设置为vuex状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!