【问题标题】:vuex module can not add element to a root statevuex 模块无法将元素添加到根状态
【发布时间】:2019-08-22 10:46:37
【问题描述】:

我想从 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 不是一个函数。

【问题讨论】:

  • 一个模块被注入到根状态中,例如:rootState[moduleName] - 我猜你的模块替换了你的artists 状态

标签: vue.js vuejs2 vuex vuex-modules


【解决方案1】:

你应该保持你的突变同步,也不要在行动中改变你的状态。考虑重构您的代码。

另一个问题是您的模块状态确实替换了您的 rootState artists

例子:

// 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);
      });
  }
}

【讨论】:

    猜你喜欢
    • 2019-04-23
    • 2018-06-01
    • 1970-01-01
    • 2019-11-17
    • 2022-01-14
    • 1970-01-01
    • 2018-09-22
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多