Vuex is a state management library for Vue. As your application continues to grow it becomes tough to handle many things.This is for someone who already knows Vue.If not please have a look at some of my previous blogs VueJSforBeginners
Note this same thing works with both Vue2 n Vue3 APi since Vue2 APi perfectly works in Vue3 but there is just a slight change which I will mention after all these
Vuex3 with Vue2
Install Vuex
After you have installed the project run
npm install vuex
index.js
We need to make a new store and here and we need to write store:store
here need to write about the store here
If we look at the console we see so many things of the store
Mutations
You can't mutate a state directly you need mutations, For mutating you to access the mutations
If we look at the Vue dev tools in the console
Here we see 3 of the mutations increment
2. Transfer to store.js
Here we are transferring everything to store.js so that everything is in a seperate file which is much more readable
As the mark is given we must default export store at the botton
In App.vue
Here we need to import
import store from './store'
No need to import store now if we use $this.store
Display Todos
Here we take an array of objects todos in store and we want to loop through it
IN store.js
In App.vue
template part in App.vue
Looping through array of objects
mapState
Here we can use mapState to get access to all of the state. Its much easier
In store.js
In App.vue
import {mapState} from 'vuex'
We see now we can easily have access to todos and isLoggedIn vis mapState
getters
We can access any property of state through mapState on the other hand if we want to filter out todos based on done and not done for that we need to use getters
App.vue
template part
in the browser
getters inside getters
in store.js
Suppose we want to get length of allTodos so here we can find out length of allTodos
In App.vue
In browser
mapGetters
Here we can just use mapGetters
import mapGetters
on the top.By this have all getters easily.
Mutation and action
Suppose we want to set both methods to increase and decreaseCounter.Here we will have to set two methods one is increase and other is decrease
In store.js
Here the mutations are commited in actions
In App.vue
Here we see we dispatch the actions
template part
mapActions
Just Like mapGetters
we can use mapActions
we need to import mapActions
at the top
Here I am going to talk about how you will install Vuex4
wih Vue3
.Remeber Vuex4
only works with Vue3
However Vuex3
works works with both.
Install Vuex4
npm install vuex@next
In package.json
dependencies if you see now its vuex4.0.2
main.js
store/index.js
Remember to export store
My way of writing it might differ from other but main things is the code working. So I believe you can now work with Vuex
with latest Vue3
Api.
Top comments (0)