DEV Community

Max Walter
Max Walter

Posted on

Simple VUEX Guide

Vuex

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.

Interacting with the Store

mapState

import { mapState } from 'vuex';

computed: {
  ...mapState([
    'title'
  ])
}

mapGetters

import { mapGetters } from 'vuex';

computed: {
  ...mapGetters([
    'title'
  ])
}

mapMutations

import { mapMutations } from 'vuex';

methods: {
  ...mapMutations([
    'ADD_SOMETHING'
  ])
}

mapActions

import { mapActions } from 'vuex';

methods: {
  ...mapActions([
    'DO_SOMETHING'
  ])
}

The Store itself

State Object:

This is how the state object could look like

state: {
    todos: [
        {id: 1, name: 'Do my Homework', done: false},
    {id: 2, name: 'Clean my Room', done: true},
    ]
}

Getters:

getters: {
  doneTodos: state => {
    return state.todos.filter(todo => todo.done)
  }
}

Mutations:

mutations: {
  increment (state, payload) {
    state.count += payload
  }
}

Actions:

Actions are similar to mutations, the differences being that:

  • Instead of mutating the state, actions commit mutations.
actions: {
  increment ({context, state}, payload) {
    context.commit("increment", payload);
  }
}

Persistent Store

// store.js
// yarn add vuex-persist
import VuexPersist from 'vuex-persist'

const store = new Vuex.Store({
  //...initialization
  plugins: [vuexPersist.plugin]
})

Top comments (0)