If more than one component needs to make use of this, we have to either duplicate the function, or extract it into a shared helper and import it in multiple places - both are less than ideal.
Vuex allows us to define "getters" in the store.
You can think of them as computed properties for stores.
As of Vue 3.0, the getter's result is not cached as the computed property does.
This is a known issue that requires Vue 3.1 to be released. You can learn more at PR #1878.
Getters will receive the state as their 1st argument:.
We can now easily make use of it inside any component:.
Note that getters accessed as properties are cached as part of Vue's reactivity system.
- You can also pass arguments to getters by returning a function.
- This is particularly useful when you want to query an array in the store:.
Note that getters accessed via methods will run each time you call them, and the result is not cached. The mapGetters helper simply maps store getters to local computed properties:. If you want to map a getter to a different name, use an object:.
As of 2022 medium.com requires you to have at least 100 followers to be eligible for the partner program.
At the time of writing this, I have 13. So please consider following me if you find this article helpful or interesting. There is an alternative approach that should probably be referred. Especially if you are working on a new project, there might be now reason to use Vuex at all. I just stumbled upon this StackOverflow post while checking out Vue 3 and this new syntax and Composition API and so on and getting to the point where I was ready to add a Vuex store.