DEV Community

Max Walter
Max Walter

Posted on

3 2

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]
})

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay