我想从 vuex 中的模块将元素推送到根中的状态。 但是我得到一个错误:rootState.artists.push不是一个功能。
//in root state store.js
state:{
artists:[]
},
modules:{
artists,
}
//in module artists.js
return firestore().collection('artists').limit(15).get()
.then((snapshot) => {
let artists = [];
snapshot.forEach(doc => {
artists.push({...doc.data(), id: doc.id })
});
rootState.artists.push(...artists);
}).catch((err) => {
console.log(err);
});
我希望应该填充根状态中的艺术家数组,但是,我得到rootState.artists.push不是一个函数。
你应该保持你的突变同步,也不要在行动中改变你的状态。考虑重构代码。
另一个问题是您的模块状态确实会替换您的 rootStateartists
。
例:
// in store.js
state:{
artists:[]
},
mutations: {
updateArtists(state, artists) {
state.artists.push(...artists);
},
},
modules:{
artistsModule,
}
// in artistsModule.js
actions: {
updateArtists(context) {
firestore().collection('artists').limit(15).get()
.then((snapshot) => {
let artists = [];
snapshot.forEach(doc => {
artists.push({...doc.data(), id: doc.id })
});
context.commit('updateArtists', artists, { root: true });
}).catch((err) => {
console.log(err);
});
}
}