Vue Mapgetters

Posted on  by admin
Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them:.

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:.

The getters will be exposed on the store.getters object, and you access values as properties:.
Getters will also receive other getters as the 2nd 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.

  1. You can also pass arguments to getters by returning a function.
  2. 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 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.