-
Notifications
You must be signed in to change notification settings - Fork 11
7. Vuex Store
Using a store to manage the state is important to every big application, that's why nuxt.js implement Vuex in its core.
Nuxt.js will look for the store directory, if it exists, it will:
- Import Vuex,
- Add
vuexmodule in the vendors bundle - Add the
storeoption 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 createStoreThe 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.
Hello, my name is Cristian Moreno.
I'm a community leader and altruistic speaker, JavaScript/Node.js evangelist and FullStack Javascript Developer. Currently co-organize Medellin.js (Biggest JavaScript user group in Colombia), Avanet and Azure Cloud Medellin communities.
I love developing things, especially ideas, giving them a new perspective and making them shine! products and applications come after I transform ideas into code; I'm passionate about software development and related stuff.