Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
State Management with Vuex Chapter 21

As we have a minuscule example, the use of a getter for this property isn't entirely


necessary, but as we scale our application(s), we'll need to use getters to filter state. Think
of these as computed properties for values in the state, so if we wanted to return a modified


version of this property for the view-layer, we could as follows:


export default {
count(state) {
return state.count > 3? 'Above three!' : state.count;
},
};

Combining elements


In order to pull this all together, we have to revisit our store/index.js file and add the


appropriate state, actions, getters, and mutations:


import Vue from 'vue';
import Vuex from 'vuex';

import actions from './actions';
import getters from './getters';
import mutations from './mutations';

Vue.use(Vuex);

export default new Vuex.Store({
state: {
count: 0,
},
actions,
getters,
mutations,
});

In our App.vue, we can create a template that will give us the current count as well as


some buttons to increment, decrement, and reset state:


<template>
<div>
<h1>{{count}}</h1>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="reset">R</button>
</div>
</template>
Free download pdf