Vuex Basics

So Vuex is very similar to Redux as far as what they are trying to accomplish. It is about creating a data store that all components can access rather than passing the data directly from component to component.  These are my quick notes on Vuex.

Creating a Store


const store = new Vuex.Store ({
    // The data we want available to rest of application
    state: {
        message: 'Hello World',
        count: 0
    },
    // These are things that change the state // synchronous
    mutations: {
        increment(state,payload){
            state.count+=payload;
        }
    },
    // Asynchronous
    actions: {
        increment(state,payload){
            state.commit('increment',payload)
        }
    },
    // These are a central way to pull data from the state
    getters: {
        message(state){
            // Formatting it for example
            return state.message.toUpperCase();
        },
        counter(state){
            return state.count;
        }
}
});

Grabbing the data from the store (Not Recommended)

Although you can do this to grab the data directly from the store – its better to use the getter. That way if you implement formatting/validation etc it can be done in one place.

Script


<script>
new Vue ({
    el: '#app',
    data() {
        return {
            welcome: 'Hello World'
        }
    },
    computed: {
        message(){
            return store.state.message;
        }
    }
})
</script>

Output (html/razor)


 <body>
        <div id="app">
        <h1>{{welcome}}</h1>
        <h2>{{message}}</h2>
        </div>
    </body>

Grabbing the data from the store using a getter
Script


<script>
new Vue ({
    el: '#app',
    data() {
        return {
            welcome: 'Hello World'
        }
    },
    computed: {
        message(){
            return store.getters.message;
        },
        count(){
            return store.getters.counter;
        }
    },
    methods : {
        pressed(){
            // Would call the mutation (synchronously)
            //store.commit('increment',10);
            // This calls the action (Asynchronously)
            store.dispatch('increment,10);
        }
    }
})
</script>

Output (html/razor)


 <body>
        <div id="app">
        <h1>{{welcome}}</h1>
        <h2>{{message}}</h2>
        <h3>{{count}}</h3>
        <button @click="pressed">Increment Counter</button>
        </div>
    </body>


Some Final Thoughts

  • Actions are async meaning that all API requests should be done in actions. Vue Docs – Actions
  • Mutations are synchronous – so these should not require any outside resource ever. Pure state manipulation only.
  • Recommended App Structure for Vue Apps

Leave a Reply

Your email address will not be published. Required fields are marked *