我有一个名为类别的 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')
但我不确定该把它放在哪里。
可以通过商店内的操作来获取数据。在操作中提交更改以更新状态。
创建商店后,您可以通过调用立即调度 fetch 操作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;
商店除了报关外还要出口
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)