Skip to content

7. Vuex Store

Khriztian Moreno edited this page Nov 8, 2017 · 2 revisions

Using a store to manage the state is important to every big application, that's why nuxt.js implement Vuex in its core.

Activate the Store

Nuxt.js will look for the store directory, if it exists, it will:

  • Import Vuex,
  • Add vuex module in the vendors bundle
  • Add the store option to the root Vue instance.
import Vuex from 'vuex'
import axios from 'axios'

const API = 'https://api.github.com'

const createStore = () => {
  return new Vuex.Store({
    state: {
      gists: []
    },
    mutations: {
      SET_GISTS_LIST (state, gists) {
        state.gists = gists
      }
    },
    actions: {
      async LOAD_GIST_LIST ({ commit }, username) {
        try {
          const { data } = await axios.get(`${API}/users/${username}/gists`)
          commit('SET_GISTS_LIST', data)
        } catch (error) {
          console.log('ERROR', error)
        }
      }
    }
  })
}

export default createStore

The fetch Method

The fetch method is used to fill the store before rendering the page, it's like the asyncData method except it doesn't set the component data.

In index.vue we are going to replace the way we check the data of the GitHub API to use Vuex. Eliminate the dependence of axios and asyncData method, replace them with fetch, and we will help you with a couple of vuex functions to bring the same data.

<script>
  import { mapState } from 'vuex'

  import GistArticle from '~/components/GistArticle.vue'

  export default {
    async fetch ({ store }) {
      await store.dispatch('LOAD_GIST_LIST', 'khriztianmoreno')
    },
    components: {
      GistArticle
    },
    computed: mapState([
      'gists'
    ])
  }
</script>

To see these steps complete, you can change to the 7-vuex-store branch in this repository.