Reading the State With Getters

Imagine if our state was a bit more complicated — think two or three objects deep — common with forms.

Instead of writing $store.state.form.username.pet[2] inside our templates, we can get the computed state and pass it to our template. This drastically cleans up the code. The Vue template should render markup and deal with outside logic as little as possible.

ES6 (preferred), ES5 below.

ES5

Simple, we map a function to a key and return the desired state inside the function. If you come from the React world, think of getters as selectors.

Back inside our Vue component, we’ve create a computed property and mapped our Vuex getter to it.

Creating computed getters

Notice how the markup is clean once again — that’s the whole point.

Here’s the shorthand to the computed getter with the help of the mapGetters function.

mapGetters helper function

One of the key features of any state containers are the amazing state inspection tools. Vue.js dev tools has a Vuex inspector out of the box.

Inspecting Vuex state with Vue dev tools

Amazing! Debugging conditions have never been any better!

If you like working with Vue and want to learn it in more depth, here’s a great book on full-stack Vue.