【问题标题】:Understanding Vuex getters and mutations了解 Vuex getter 和 mutation
【发布时间】:2019-08-21 21:08:44
【问题描述】:

假设我有一个这样的 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 结果被缓存(我认为?)这两种方法真的差不多吗?是抛硬币决定走哪条路,还是有一个我可以用来决定的委托人? -- 谢谢

【问题讨论】:

    标签: javascript vuex


    【解决方案1】:

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

    【讨论】:

    • 谢谢。这似乎也很聪明,因为将文档与添加/删除分开将是零成本。我会用这个答案。
    猜你喜欢
    • 2020-02-20
    • 2021-09-15
    • 1970-01-01
    • 2018-12-08
    • 2018-05-07
    • 1970-01-01
    • 2020-05-29
    • 2021-09-03
    相关资源
    最近更新 更多