Vuex examples — State, Getters & Mutations (Part 1)
“Don’t wait to be perfect to share your knowledge to everyone”
and also an expert once said, “Done is better than perfect”.
So, here I am, trying to share what I have got so far.
As you can see on the title, I am going to share basic understanding about Vue.js and it’s state management — Vuex. This is going to be a series of Vue.js and Vuex which I divide into some series.
Add Vuex into Vue.js Project
First thing first, I assume that you are already create new Vue.js project.
There are many ways to add Vuex into your existing project. Here I use NPM to add Vuex package. With NPM installed in your machine, you can simply type:
npm install vuex --save
yarn add vuex # if you are using yarn instead of npm
Or if you want to see the full guide, please go to the official guide Vuex Intallation.
State in Vuex is the main aspect that we should keep in-mind. Because Vuex is all about managing the state of our element in our web apps. Here is my code https://codesandbox.io/s/vuex-examples-b155q if you want to take a look. To make state, you can simply add variable in inside your state:
If you look at it, you will find that state is like a variable. The difference is its like a global variable that we can access anywhere in our components.
Actually we can access state in our Vuex store directly, but it’s suggested not to do so. Instead we can access our state using Getters, it’s like set and get in Java. It’s also important to notice that Getters seems like computed properties in Vue components because it’s reactive for changes. To access state, you can simply do like this:
If Getters looks like get, you can guess what mutations are. Simply put, Mutations is kind of “mutations” (changes). pretty self explanatory. It is used to change the state. Even though you can change the state directly, still you are suggested to use Mutations if you want to change it. It’s related to how the vuex reacts to the changes we make to the state.
Your app.vue looks like…
Practice, Practice, Practice
In order to have a clear understanding, you have to get dirty. It means that you need to try many times though sometimes you feel like it gets a bad result, just keep trying and try and keep track of this series because I am going to share about a case why you should use getters instead of access state directly in the next post. Leave your comment and let me know what you think.