首页 > 解决方案 > 了解 Vuex getter 和 mutation

问题描述

假设我有一个像这样的 vuex 商店......

state: {
  docs: null, 
  adds: [],
  deletes: [],
},
actions: {
  // initialize docs to an array of objects
  init (context, payload) {
  }
}
getters: {
  // get the docs plus the adds, minus the deletes
  docs (state) {
  }
},
mutations: {
  // add a doc, keeping track that it was added
  addDoc (state, payload) {
  }
  // remove a doc, keeping track that it was deleted
  removeDoc (state, payload) {
  }
}

我想我有两种选择可以实现:要么在 setter 上改变 docs 数组,要么在 getter 上计算数组的有效值。这些想法中的一个在反应性或性能方面是否比另一个差得多?

换句话说:

// choice 1: really mutate the docs
addDoc (state, payload) {
  state.adds = [...state.adds, ...payload]
  state.docs = _.without([...state.docs, ...payload], state.deletes)
}

// choice 2: mutate the docs in effect, via the getter
addDoc (state, payload) {
  state.adds = [...state.adds, ...payload]
}

// choice 2, in getter
docs(state) {
  return _.without([...state.docs, ...payload], state.deletes)
}

假设不经常进行突变,并且经常调用 getter,我是否会为选择 2 付出计算代价?或者,由于 getter 结果被缓存(我认为?)这两种方法真的差不多吗?是抛硬币决定走哪条路,还是有一个我可以用来决定的委托人? - 谢谢

标签: javascriptvuex

解决方案


嗯,是的,吸气剂被缓存了。所以在这种情况下,我猜只是抛硬币。就个人而言,我更喜欢在 getter 上进行计算。


推荐阅读