DEV Community

Islam Ahmed Hassan
Islam Ahmed Hassan

Posted on

Vuex is a state management pattern

Vuex

Vuex is a state management pattern + library for Vue.js applications

The state, the source of truth that drives our app;
The view, a declarative mapping of the state;
The actions, the possible ways the state could change in reaction to user inputs from the view

Usage

To understand Vuex it’s much easier if you first understand the problem that it’s designed to solve.

1 - Sharing data between components especially from child to
parent now it’s much easier .

2 - Imagine you have centralized store for saving every single
data and this store shared between all other components Dreams
come true .

3 - Make your asynchronous requests in one place for dealing with
API so , your integration become more organized and secure .

Installation

NPM

npm install vuex --save
Enter fullscreen mode Exit fullscreen mode

Yarn

yarn add vuex
Enter fullscreen mode Exit fullscreen mode

When used with a module system, you must explicitly install Vuex as a plugin:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
Enter fullscreen mode Exit fullscreen mode

You don’t need to do this when using global script tags

CDN

<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"&gt;&lt;/script>
Enter fullscreen mode Exit fullscreen mode




Structure

State

Single object contains all your application level state and serves as the “single source of truth.” This also means usually you will have only one store for each application

Getters

Used to compute derived state based on store state , vuex allows us to define “getters” in the store. You can think of them as computed properties for stores. Like computed properties, a getter’s result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed.

Mutations

This is the only way to actually change state in a Vuex store is by committing a mutation.

Actions

Actions are similar to mutations, the differences being that:

  • Instead of mutating the state, actions commit mutations.

  • Actions can contain arbitrary asynchronous operations.

**As you can see in the **Vuex docs,, it comes with examples**

Conclusion

Vuex provides advanced topic and utilities than we were able to cover in this article.

This is a mere introduction to it, and by no means a comprehensive one. But we covered the part that is most often the biggest obstacle to adoption: understanding the concept and usage .

Oldest comments (0)