在vuex中使用助手功能

时间:2018-08-10 08:42:30

标签: vue.js vuex

在vuex模块中,我从2个不同的来源获取数据(文档和收藏夹),我需要遍历文档并将收藏夹分配给文档。

我在vuex模块之外创建了一个可重用的函数来帮助我做到这一点:

const bindFavoriteToDocument = (documents, favorites) => {
  // reset selected favorites
  favorites.forEach(item => {
    item.selected = false
  })
  documents.forEach(item => {
    var favs =
    favorites.filter(f => {
      var filter = f.favoriteDocuments.filter(
        d => d.document === parseInt(item.id) && d.source.toLowerCase().trim() === item.agency.toLowerCase().trim()
      )
      return !!filter.length
    }) || []

    favs.forEach(item => {
      item.selected = true
    })

    item.favorites = favs
    item.favoriteIds = _.pluck(favs, 'id')
    item.active = false
  })
  return documents
}

当收藏夹对象的所有内容都更新时,我调用此函数来刷新分配给文档的收藏夹列表。

  deleteFavorite: async ({ dispatch, commit, rootGetters }, payload) => {
    const response = await remove(config.PORTAL_API + 'api/favorite/delete/' + payload.id, rootGetters.token)
    if (response) {
      await dispatch('getFavorites')
      const documents = bindFavoriteToDocument(rootGetters['document/documents'], rootGetters['document/favorites'])
      commit('setDocuments', documents)
    }
  }

编辑收藏夹后,我会在控制台中看到此错误:

  

错误:[vuex]不要在突变之外变异vuex存储状态   处理程序。

如何在bindFavoriteToDocument中创建不直接改变存储状态的文档和收藏夹的新副本?

我尝试过:

const bindFavoriteToDocument = (documents, favorites) => {
  let favoriteList = favorites
  let documentList = documents
  .
  .
  .
  return documentList
}

但这没用。

1 个答案:

答案 0 :(得分:1)

只需创建将调用bindFavoriteToDocument的突变并设置文档,就可以避免此警告:

  // in actions
  deleteFavorite: async ({ dispatch, commit, rootGetters }, payload) => {
    const response = await remove(config.PORTAL_API + 'api/favorite/delete/' + payload.id, rootGetters.token)
    if (response) {
      await dispatch('getFavorites')
      commit('bindFavoritesAndSetDocuments', { docs: rootGetters['document/documents'], favs: rootGetters['document/favorites'] } );
    }
  }

  //in mutations 
  bindFavoritesAndSetDocuments: (state, { docs, favs }) => {
      const documents = bindFavoriteToDocument(docs, favs);
      // set docs if necessary
  }