2👍
Both Vuex getters
and computed component properties are JavaScript getters.
The long syntax of a computed is:
computed: {
yourComputed: {
get: function() { return expression }
}
}
equivalent of:
computed: {
yourComputed() { return expression }
}
and you can always define setters for computed:
computed: {
yourComputed: {
get: function() { return expression },
set: function(value) {
// dispatch an action or commit a mutation using value
}
}
}
This, combined with Vue’s reactivity (or change detection mechanism) means that once they’re run once, every time they’re requested again Vue will serve the previously computed value – that’s why they’re called computed – (without actually re-running the code) until the moment any of the dynamic bits (references) change. When references change, the getter (whether it’s a Vuex getter or a computed property) is rerun and all places where its referenced are notified (and those are re-run/re-rendered, in turn).
The only difference between the two cases is: Vuex getters are cached at store level, computed props are cached at component level.
In terms of both performance and change detection they’re basically the same (internally they use the same mechanism).
Now, if you’re only using this in one single component, the recommendation is not to use Vuex, as you’ll have unnecessary additional boilerplate code around your data.
You’re better off using a private store inside your component (either Vue.observable() or a Vue instance – before Vue.observable() was a thing, that was the way to create a basic Store without all the bells and whistles a Vuex store comes with).
Note: The mentioned alternatives allow you to expose the component’s private store. If you don’t need to expose it, don’t bother: each component already has a private store: the data
function (exposed to template). All you need to do is declare the reactive props upfront and from that point on the component will react to applied changes.
As already stated in the comment below your question, the choice here should not be based on code performance (as it’s basically the same), but based on development and code management performance.
On how much your project will benefit from the order/structure Vuex comes with, in the long run:
- how complex will your app get in time,
- how many developers are/will be working on it and how well defined are the project’s private conventions (if any)
- how decoupled do you want/need data management and components to be)
- how many iterations of this app are you expecting/foreseeing?
The more complex the project (codebase size, data structure complexity, app logic complexity, number of app iterations, number of developers), the more benefit you’ll get from using Vuex, IMHO.