Vuex is a
library/state management pattern for use with Vue JS. It allows us to create a
centralized data store which can be accessed by all components in an app. This
store is known as a “single source of truth”.
Managing the state
inside your application is referred to state management. It can also make sure
that the UI of your application is always reflecting by the changes of your
Vuex is very similar to Redux which is used by React JS.
This is a basic
illustrated functionality of Vuex:
Why use Vuex?
Components need to share state in many cases.
Vuex provides a single source of truth for data/state
No need to pass events up and props down through multiple
Global state is “reactive”
Let’s just go to
standard Vue JS application and how we set it without using Vuex:
This is just a simple to-do application. Here we have got a root component and we got two different components nested within that which are Dashboard and TODO List. And, under those we have other two components. Here, if we use TODO items data to its’ child component, we have to use props to send the data. Then in Add TODO if we want to add a new TODO, we have to trigger an event to update the TODO list in its parent component. After that, the TODO List component again triggers an event to update the root component. So, you can see this is a long process to follow. For small project this process will be okay. But, if the application is large enough and we have much more data to handle this process, it will be really hard to follow.
If we use Vuex for the same application, it will look like this:
Here, we have one central store which is storing the TODO items. It can be accessed directly from any component. No need to use any props, it can be accessed using most known as “getters”. Even if we want to change the data, for example add a new TODO in “Add TODO” component we just need a mutation to the data. By doing this all component will get the updated data automatically. We do not have to use any event to do that. You see, it’s very easy once you understand the functionalities of Vuex.
Terms of Vuex
State – data (TODOs, posts, token, etc)
Getters – get pieces’ values from state
Actions – called from components to commit a mutation
Mutations – Mutate the state
Here is a basic
code structure of how we can use vuex in a Vue JS app.
If you want to learn more about it or you need any dynamic web application using Vue JS, just get in touch- https://augnitive.com/