了解Vuex吸气剂和突变

时间:2019-03-31 15:44:42

标签: javascript vuex

假设我有一个像这样的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) {
  }
}

我认为我有两种选择来实现:要么使设置程序上的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付出计算上的损失?还是因为缓存了吸气剂的结果(我认为?),这两种方法真的差不多吗?这是一个抛硬币的路,还是我可以用来决定的原理? -谢谢

1 个答案:

答案 0 :(得分:1)

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