Numerous Ways to a Vuex Store

Vue is great and Vuex makes it greater. But, how do you use them stores?

Vuex: You exy thing

Vuex makes it a breeze to handle states, mutations and actions in Vue. All I need to do is follow a couple of steps.

Step 1: Select Vuex as an option when you create the Vue application (or, you can always add it later)

Step 2: Vuex is already added for you - see below code in main.js -

// main.js

// ... code

import store from "./store";

//..

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");

The src/store folder has an index file created by default. You can use it as-is or add modules for more fun.

It is time to put the store to some good use. You can access a store as-is or with modules using one of the following means -

  1. State: Access state to read variable values
  2. Mutations: Update values through mutations
  3. Actions: Can also update state, but it is good to go through mutations

You can use these store functions in rest of Vue.

Option 1: Use store helpers in components and views

Create a simple import statement and access your state variables.

<!-- any *.vue file -->

<template>
  <!-- lot of code -->

  {{ first_name }}

  <br /><br />
  <label for="firstName">First Name</label>
  <input name="firstName" type="text" v-model="first_name" />

  <!-- code -->
</template>

<script>
  import { mapState, mapMutations } from "vuex";

  // more code

  export default {
    computed: {
      ...mapState("contact", ["first_name"]),
    },

    methods: {
      ...mapMutations("contact", ["setFirstName"]),

      validateAndUpdateFirstName(val) {
        if (val.length > 2) this.setFirstName(val);
        else throw new Exception("Are you sure you are a real person?");
      },
    },
  };
</script>

This is cool, but you can save a bunch of “typing” - which brings us to Option 2.

Option 2: Use Pathify

Instead of doing a mapState and mapMutations - you let Pathify handle everything for you.

<template>
  <!-- code -->
</template>

<script>
  import { sync } from "vuex-pathify";

  export default {
    computed: {
      ...mapSync("contact", "first_name"),
      // you can access first_name or update it directly
    },

    methods: {
      validateAndUpdateFirstName(val) {
        if (val.length > 2) this.first_name = val;
        else throw new Exception("Are you sure you are a real person?");
      },
    },
  };
</script>

Option 3: Use store as a function

You could just use store to access access or update state. This more common in store modules.

// src/store/contact.js

import store from "../store";

// ... code

export default {
  actions: {
    async updateContact({ commit }, params) {
      // ..

      store.set("action/updateCall", actionData);
      // `commit("action/updateCall",actionData, { root: true }) does the same thing - but only sane people do that
    },
  },
};
// ...code

Accessing store from a router is similar to the above depiction.

You could import the store in your components/views as well and do the same, but there is a shortcut -

<template>
  <!-- code -->

  {{ firstName }}

  <!-- code -->
</template>

<script>
  export default {
    computed: {
      firstName() {
        return this.$store.state.contact.first_name;
      },
      // you can access first_name or update it directly
    },

    methods: {
      validateAndUpdateFirstName(val) {
        if (val.length > 2) this.$store.commit("setFirstName", val);
        else throw new Exception("Are you sure you are a real person?");
      },
    },
  };
</script>

Recommendation

Use Pathify. Period.

If you don’t want to use a third party library - use Vuex helper functions like mapState. You will make it easier on yourself by standardizing the state access/updates throughout the project, and more importantly, cutting across development teams.

Last updated:
Categories: Vue
Tags: VueJS
comments powered by Disqus