Reputation: 757
Let's say I have a vuex store like this...
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) {
}
}
I think I have two choices to implement: either mutate the docs array on the setters, or compute the effective value of the array on the getter. Is one of these ideas much worse than the other either in terms of reactivity or performance?
In other words:
// 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)
}
Assuming the mutation is made infrequently, and the getter is called frequently, am I paying a computational penalty with choice 2? Or, since the getter results are cached (I think?) are the two approaches really about the same? Is it a coin toss about which way to go, or is there a principal I can use to decide? -- Thanks
Upvotes: 1
Views: 80
Reputation: 126
Hm yes, getters are cached. So in this case just flip a coin I guess. Personally, I prefer to make compute on getters.
Upvotes: 1