Vuex Quick Snippets

main-hero-img-11-scaled.jpg

Intro to Vuex

Vuex is a state management library for Vue. So, first question, what is a state then ?

the particular condition that someone or something is in at a specific time.

– google dictionary

According to the google, a state is a condition at a specific ==time==. You should pay extra attention to the word ‘time’ here. That means, state is useless except binding it to a specific time.

I ==was== a student, ==now== I am a CTO.

If the first question is clear, now we are ready for the second the question : why we need Vuex ? Or by other means why we need a Vuex store? Or also the same question can be as, why we need a state in Vuex while we already have a data object in our Vue components?

Q: why we need a store in Vuex while we already have a data object in our Vue components?

A: To be clear, let’s dive into data and see what it dose :

A data object in vue components is somewhere we can store ‘strings’, ‘arrays’, and ‘objects’, so that we can use them to setup our HTML dynamically (using interpolation), or we can store user inputs (two-way data binding).

It is very clear that, by this means we have successfully separated our business logic in the Javascript and the view logic in the template, we can show data on the template or also can retrieve data from the template.

That is useful and almost the core idea of Vue.js. But you should also be noticed that, you can change the data object in both sides , on the template or on the javascript.

Due to the nature of Vue.js, you can even use components nested, that means, you will have several data objects in your projects, sending and retrieving data between components can be tricky.

You have to make sure that all of your data clones updated synchronously, in all of your data objects, included in all of your components, although you can write the logic by hand, if you have that time and energy, ………

The idea of Store or Vuex is to use a Frontend Database in your project. If anyone (any of your components) wants to retrieve or update any data (state) then they should call the Database (Store) to do so, in that way, you don’t have to worry about the complicated procedures.

How to use Vuex in real-life projects?

API-> actions: axios (async)
actions -> mutations: commit (sync)
mutations -> state:push (sync)
state -> getters:filter
state -> View: store.state.x
getters -> View: store.getters.x


View --> actions: 1-1 dispatch
View --> mutations: 2 commit
actions --> mutations: 1-2 commit (sync)

Above is the detailed working process of using Store in real-life projects.

Here I will show the detailed usage of this process using a real-life shop app. (Elab)

We have a slider component (View above) in our project, which shows carousels on the home page.

<template>
  <v-carousel
    cycle
    height="400"
    hide-delimiter-background
    show-arrows-on-hover
  >
    <v-carousel-item
      v-for="(slide, i) in slides"
      :key="i"
    >
      <v-sheet
        :color="colors[i]"
        height="100%"
      >
        <v-row
          class="fill-height"
          align="center"
          justify="center"
        >
          <div class="text-h2">
             Slide
          </div>
        </v-row>
      </v-sheet>
    </v-carousel-item>
  </v-carousel>
</template>
<script>
  export default {
    data () {
      return {
        colors: [
          'indigo',
          'warning',
          'pink darken-2',
          'red lighten-1',
          'deep-purple accent-4',
        ],
        slides: [
          'First',
          'Second',
          'Third',
          'Fourth',
          'Fifth',
        ],
      }
    },
  }
</script>
<style lang="scss">
    
</style>

image-20210802125345004

We need a way to retrieve sliders data (banners below in the API side) from the REST API.

There are several ways to do so :

  1. Retrieve data within the component (using mounted)
  2. Retrieve data first from API , save data to Store, then update view using Sliders state.

The first method of course works and is much more simple that the second in our case, however, we will use the second method here, and we will explain later why.

First let’s install and enable some packages (modules):

yarn add --exact @nuxtjs/auth-next
yarn add @nuxtjs/axios
yarn add @nuxtjs/proxy

Add modules to nuxt.config.js:

  modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
    // https://go.nuxtjs.dev/pwa
    '@nuxtjs/pwa',
    '@nuxtjs/auth-next',
    '@nuxtjs/proxy',
  ],

Enable Auth (because our API endpoints requires authentication):

 router: {
    middleware: ['auth'],
  },

Enable proxy :

 axios: {
    proxy: true,
  },

Proxy settings for our API:

proxy: {
    '/auth/': 'http://127.0.0.1:8000/',
    '/api/': 'http://127.0.0.1:8501/api/v1/shop/',
  },

and setup authentication:

auth: {
    redirect: {
      login: '/login',
      logout: '/',
      // callback: '/login',
      home: '/',
    },
    strategies: {
      local: {
        scheme: 'refresh',
        token: {
          property: 'access',
          global: true,
          // required: true,
          // type: 'Bearer'
        },
        refreshToken: {
          property: 'refresh',
          data: 'refresh',
          maxAge: 60 * 60 * 24 * 30,
        },
        user: {
          property: 'user',
          // autoFetch: true
        },
        endpoints: {
          login: { url: 'auth/token/', method: 'post' },
          refresh: {
            url: 'auth/token/refresh/',
            method: 'post',
          },
          logout: { url: 'auth/logout/', method: 'post' },
          user: { url: 'auth/me/', method: 'get' },
        },
      },
    },
  },

Then, we have to create a store for our Sliders.

image-20210802130533504

Then we created a state for our sliders in store/sliders.js

export const state = () => ({
    list: []
  })