javascript - 了解 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 结果被缓存(我认为?)这两种方法真的差不多吗?是抛硬币决定走哪条路,还是有一个我可以用来决定的委托人? - 谢谢
解决方案
嗯,是的,吸气剂被缓存了。所以在这种情况下,我猜只是抛硬币。就个人而言,我更喜欢在 getter 上进行计算。
推荐阅读
- javascript - How to filter a list with max value of an attribute using map-reduce in typescript?
- json - How to query nested array of jsonb
- flutter - Dart: Future
.then(_) requires callback with parameter - php - 如何在 php-fpm 中定义以美元符号开头的 env 值
- javascript - 使用 JavaScript/jQuery 对数组进行表单验证
- git - 如何让我的 git 项目对 GitHub 可见?
- firebird - Firebird 相当于 MySQL 表分区
- angular - 当我单击它时,Angular 表单提交按钮不起作用
- java - 初始化 MapState 的内容
- python - python找到唯一并按字母顺序排列