Vuex 101
Vuex is a state management library for Vue.js.
It has five main concepts:
- State - App level state container
- Getter - Used to access state data in the component
- Action - perform computations on state and fetch data from remote API
- Mutation - Commonly called by Action to change State's data
- Module - containerized for of the above 4. For example: Todos Module, Auth Module...
Code Snippets
- create a folder named store inside src.
File /src/main.js
import Vue from 'vue'; import App from './App.vue'; import store from './store'; new Vue({ store, render: h => h(App) }).$mount('#app');
File /src/store/index.js
import Vuex from 'vuex'; import Vue from 'vue'; import todos from './module/todos'; // Load Vuex Vue.use(Vuex); // Create store export default new Vuex({ modules: { todos } });
File /src/store/modules/todos.js
import axios from 'axios'; // we use axios to fetch data from remote API const state = { todos: [] }; const getters = { allTodos: (state) => state.todos; }; const actions = { async fetchTodos({commit}) { const reponse = await axios.get('jsonplaceholder.typicode.com/todos'); commit('setTodos', reponse.data); } }; const mutations = { setTodos: (state, todos) => (state.todos = todos); }; export default { state, getters, actions, muations };
File /src/components/todos.vue
<template> <div> <h3> Todos </h3> <div class="todos"> <div v-for="todo in allTodos" :key="todo.id"> {{ todo.title }} </div> </div> </div> </template> <script> import { mapGetters, mapActions } from 'vuex'; export default { name: 'Todos', methods: { ...mapActions(['fetchTodos']) }, computed: { ...mapGetters(['allTodos']) }, created() { this.fetchTodos() } } </script> <style> </style>
Top comments (0)