Vue Getters

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.

Like computed properties, a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed.

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

Change Tracking

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.

# Property-Style Access

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

In the previous post we saw how and when to use computed properties. In this post, I want to show you how to use getters and setters with computed properties.

More Vue Tutorials

Computed properties are getter-only by default, but if you need to, you can also specify a setter.

To do this, we actually need to change our computed property from a function to an object with two properties; get and set.