假设我有一个像这样的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数组进行更改,要么在获取器上计算该数组的有效值。这些想法之一在反应性或性能方面是否比另一个想法差很多?

换一种说法:

// 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付出计算代价?或者,由于缓存了吸气剂的结果(我认为呢?),这两种方法真的差不多吗?是抛硬币走哪条路,还是有我可以用来决定的原理? - 谢谢

最佳答案

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

关于javascript - 了解Vuex setter/getter 和突变,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55442611/

10-12 15:46